Dictionary Django Filter Model

How to make a filter in the Django Model using a dictionary, not method arguments? Here is what I have 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... 

The side question is, is there a better way to set dictionary values ​​than what I'm doing above? For example, triple, but in such a way that the value does not exist, if it did not exist?

 sort_params['sort'] = sort if not None else '' 
+8
django django-models
source share
2 answers

You use a dictionary to pass keyword arguments as follows:

 models.Design.objects.filter(**sort_params) 

There is no built-in way to conditionally set the 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) 
+15
source share

The answer above is correct, and I suggest a more efficient option.

here request.GET - QueryDict Just translate it into a dictionary like this

kwargs = dict(request.GET)

and now filter it

models.Design.objects.filter(**kwargs)

+4
source share

All Articles