Login

Search in a model spanning relations

Author:
lbolognini
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Tags:
search
Score:
3 (after 3 ratings)

By popular demand an example of search in models that spans more realtions.

Keep a list of Q, filter the None away, feed the rest to .filter()

Credit goes to Carlo C8E Miron for the idea... cheers buddy! ;)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#get the values from form.clean_data
district = form.clean_data["district"]
min_price = form.clean_data["min_price"]
max_price = form.clean_data["max_price"]
property_type = form.clean_data["property_type"]
available_to_move_in = form.clean_data["available_to_move_in"]
available_for = form.clean_data["available_for"]
furnished = form.clean_data["furnished"]

#bind data to dict keys
qparams = dict(
            district=district, 
            min_price=min_price, 
            max_price=max_price, 
            property_type=property_type, 
            available_from=available_to_move_in,
            available_for=available_for,
            furnished=furnished
            )

#keep list Q
qsets = dict(
          district=Q(property__district=district), 
          min_price=Q(property__houselet__rent_price__gte=min_price),
          max_price=Q(property__houselet__rent_price__lte=max_price),
          property_type=Q(property__property_type=property_type),
          available_from=Q(property__available_from=available_to_move_in),
          available_for=Q(property__houselet__available_for=available_for),
          furnished=Q(property__houselet__furniture_option=furnished),
          )

#filter out the Q that have None values
final_query = [qsets[k] for k in qsets.keys() if qparams[k] is not None]

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

More like this

  1. filter/search a newforms select widget by miracle2k 7 years, 7 months ago
  2. Text Highlighting Filter by girasquid 6 years, 4 months ago
  3. Tags & filters for rendering search results by exogen 7 years ago
  4. CSV Exporting of Model Data by monokrome 5 years, 5 months ago
  5. CSV Exporting of Model Data by monokrome 5 years, 5 months ago

Comments

ubernostrum (on February 27, 2007):

See also snippet 32, which (I think) is a slightly faster and cleaner way to do this.

#

Please login first before commenting.