#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)
Comments
See also snippet 32, which (I think) is a slightly faster and cleaner way to do this.
#