On 19 jan, 18:04, "Thiago F. Crepaldi" <togn...@gmail.com> wrote:

Absolutely not an answer to your question, but...

> below is the code required. I hope you can help me =)
>
#*****************************************************************************************************************************************************************
> #  searchFeature
 
#*****************************************************************************************************************************************************************
> def searchFeature(request, view = None):
>     if request.method == 'POST':
>         form = SearchFeatureForm(request.POST)
>         if form.is_valid():
>             # Perform the query
>
>             ftrQuery = Feature.objects.all().order_by('featureId',
> 'pk')

Since your going to filter this out, starting by querying all is
useless (thanks to querysets being lazy, it's at least _only_ useless.

Remember that Django has Q objects for building complex queries, and
that you can just collect Q objects in a list, then "or" or (like in
this case) "and" them together in just one pass.

>
>             # Remove empty fields and start filtering
>             if request.POST.__getitem__('featureId') != "":

First point : you should never directly access __magic_methods__ in
Python - they are here as implementation for operators. In this case,
you want:

               if request.POST.get('featureId', '') != '':

Second point: since empty strings eval to false in a boolean context,
you don't have to explicitely compare them with the empty string. IOW:

              if request.POST.get('featureId, ''):

>                 ftrQuery = ftrQuery.filter(featureId__contains =
> request.POST.__getitem__('featureId')).distinct()


Third point : you're doing the same access twice. Better to do it just
once:

            featureId = request.POST.get('featureId, '')
            if featureId:
                 # code here

While we're at it, attribute lookup is a somewhat costly operation in
Python, specially when the attribute resolves to a method. So if
you're going to heavily use the same method of the same object, it's
better to alias it to a local name:

         get_from_post = request.POST.get

         featureId = get_from_post('featureId, '')
         if featureId:
                 # code here


While we're at it : your form object is supposed to give you access to
the validated (and possibly converted) data extracted from the
request. Is there any reason to not use this feature ?

Next point : you can pass dict objects to Queryset.filter(), (or to Q
objects) using the ** notation (cf the section of the official Python
tutorial about functions and named / keyword arguments). So you could
greatly simplify you code:

filters = [
   # fieldname, lookup
   ("featureId", "featureId__contains"),
   ("name", "name__icontains")
   ("pf", "platform"),
   ("state", "state"),
   ("db", "drumbeat__pk"),
   # etc
   ]

queries = []
add_q = queries.append
for fieldname, lookup in filters:
    value = get_from_post(fieldname, '')
    if value:
        add_q(Q(**{lookup:value}))


# now "and" the Q objects:
filters = reduce(lambda q1, q1 : q1 & q2, filters)

# and do the query:
if filters:
    queryset = Feature.objects.filter(filters)
else:
    queryset = Feature.objects.all()

queryset = queryset.order_by('featureId', 'pk')

This can not apply to all your query construction (there are some
complex cases in it), but it should already help uncluttering it for
all the simple cases.

(snip)

>             from datetime import date

Better to put import statements at the module's top-level.

>             #Only way I could find to select with COUNT without
> writting the SQL code.

You might have a look at the example snippet for the 'extra' method of
querysets.



>             if queryTeamSizeLow != '':
>                 for item in ftrQuery:
>                     if item.teammember_set.count() < int
> (queryTeamSizeLow):

Oh my. Pity this poor computer, and at least convert queryTeamSizeLow
to an int only once...


>                         ftrQuery = ftrQuery.exclude
> (featureId=item.featureId)
>
>             if queryTeamSizeHigh != '':
>                 for item in ftrQuery:
>                     if item.teammember_set.count() > int
> (queryTeamSizeHigh):
>                         ftrQuery = ftrQuery.exclude
> (featureId=item.featureId)


Ok. Some things are better done building raw sql queries. Django's ORM
is here to help with the easy and boring 80%, not to replace SQL.

My 2 cents...

(snip)
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to