Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Filter Model by Dictionary

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 ''
like image 880
JREAM Avatar asked Apr 15 '13 15:04

JREAM


2 Answers

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)
like image 106
Pavel Anossov Avatar answered Nov 14 '22 23:11

Pavel Anossov


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)

like image 35
Vamsidhar Muggulla Avatar answered Nov 14 '22 21:11

Vamsidhar Muggulla