Question: Dynamic filter in Django


Dynamic filter in Django

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

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 =['filter1'], filter2 =['filter2'], filter3 =['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
    if key in ['filter1', 'filter2', 'filter3']:
        filters[key] = value


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


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

filters = {
    key: value
    for key, value in
    if key in ['filter1', 'filter2', 'filter3']

Source Show
◀ Wstecz