How does one do a filter on a Django Model using a Dictionary rather than method arguments? This is what I have right here:
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 = {}
if sort is not None:
sort_params['sort'] = sort
if sort_price is not None:
sort_params['sort_price'] = sort_price
if sort_mfr_method is not None:
sort_params['sort_mfr_method'] = sort_mfr_method
# The Model Query
design_list = models.Design.objects.filter(sort_params)
# etc...
Side Question, is there a better way set the dictionary values than what I'm doing above? Such as a ternary, yet in a way that would make the value not exist if it's none?
sort_params['sort'] = sort if not None else ''
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With