Login

Updated version of #31

Author:
ubernostrum
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Score:
10 (after 10 ratings)

This is, I think, a slightly cleaner implentation of what snippet 31 is trying to do; by starting off with a dictionary containing the things we want to look for, and using a list comprehension to kill anything which comes out of the form as None, we can avoid some of the intermediate data structures the other snippet was using, and hopefully get better performance.

This is also quite a bit more maintainable, because supporting additional options now only requires adding a new key/value pair to qdict.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# It's easier to store a dict of the possible lookups we want, where
# the values are the keyword arguments for the actual query.
qdict = { 'available_for': 'property__houselet_available_for',
          'available_to_move_in': 'property_available_from',
          'district': 'property__district',
          'furnished': 'property__houselet__furniture_option',
          'max_price': 'property__houselet__rent_price__lte',
          'min_price': 'property__houselet__rent_price__gte',
          'property_type': 'property__property_type'
        }

# Then we can do this all in one step instead of needing to call
# 'filter' and deal with intermediate data structures.
q_objs = [Q(**{qdict[k]: form.clean_data[k]}) for k in qdict.keys() if form.clean_data.get(k, None)]

search_results = Ad.objects.select_related().filter(*q_objs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

lbolognini (on March 3, 2007):

Hi James,

thanks for doing this, only thing is that in q_objs Q can't be an expression. I'll be posting a rather more verbose version of my first snippet soon... sylistic improvements/corrections/suggestions still very welcome!

Ciao, Lorenzo

#

ubernostrum (on March 12, 2007):

Just updated it with the way I should have written it in the first place, using dictionary unpacking to handle the keyword arguments to Q. It introduces quite a few more dictionary instantiations, but still keeps the maintainability of the original.

#

lbolognini (on March 13, 2007):

Very nice James, thanks!

#

Please login first before commenting.