32👍
✅
You use a dictionary to pass keyword arguments like this:
models.Design.objects.filter(**sort_params)
There’s no built-in way to conditionally set a dict key, but if you do this a lot, you can write your own:
def set_if_not_none(mapping, key, value):
if value is not None:
mapping[key] = value
class StoreView(TemplateView):
def get(self, request):
# A bunch of gets
sort = request.GET.get('sort')
sort_price = request.GET.get('sort_price')
sort_mfr_method = request.GET.get('mfr_method')
# The params tpsort by
sort_params = {}
set_if_not_none(sort_params, 'sort', sort)
set_if_not_none(sort_params, 'sort_price', sort_price)
set_if_not_none(sort_params, 'sort_mfr_method', sort_mfr_method)
# The Model Query
design_list = models.Design.objects.filter(**sort_params)
12👍
the above answer is right and I suggest some more efficient one.
here request.GET
is QueryDict
Just convert it into a Dictionary like this
kwargs = dict(request.GET)
and now filter it
models.Design.objects.filter(**kwargs)
- Error Using CheckConstraint in Model.Meta along with Django GenericForeignKey – Joined field references are not permitted in this query
- Why is checking if two passwords match in Django so complicated?
- How to avoid creating test database for testing in django?
Source:stackexchange.com