- Author:
- lbolognini
- Posted:
- February 27, 2007
- Language:
- Python
- Version:
- Pre .96
- 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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 4 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
See also snippet 32, which (I think) is a slightly faster and cleaner way to do this.
#
Please login first before commenting.