Question: Dynamic filter in Django

Question

Dynamic filter in Django

Answers 1
Added at 2017-11-08 15:11
Tags
Question

In my app, I have a form. Depending of the form, one or many filters could be configured by the user.

In my view, I have for exemple :

query = Test.objects.filter(filter1 = request.post['filter1'], filter2 = request.post['filter2'], filter3 = request.post['filter3'])

So, sometimes filter1, filter2 or filter3 could not exist.

If any filters doesn't exist, I just want to ignore the filter.

I could do a script with many "IF" conditions but may be there is a smart solution ?

Thanks for your help !

Answers to

Dynamic filter in Django

nr: #1 dodano: 2017-11-08 15:11

You could do something along the lines of:

filters = {}

for key, value in request.post.items():
    if key in ['filter1', 'filter2', 'filter3']:
        filters[key] = value

Test.objects.filter(**filters)

Where the list is a list of keys that you are intending to filter by


Edit

As Thomas Junk suggested you can make it a lot cleaner with a comprehension:

filters = {
    key: value
    for key, value in request.post.items()
    if key in ['filter1', 'filter2', 'filter3']
}

Test.objects.filter(**filters)
Source Show
◀ Wstecz