M
M
Michael2017-08-15 15:21:58
Django
Michael, 2017-08-15 15:21:58

How to organize search with multiple parameters in django?

Good afternoon. Prompt idea how to organize search with several parameters.
Search works on ajax. There are 7 search fields in total. It is necessary to take into account all the options in which order the user can start the search.
For example, I will call the field by number, fields 1 and 2; 1 and 2 and 3; 4 and 7; 7 and 4 and 1
The logic is in what, there was an option for each field to hang up an event and send data, in view already check what is there and make queries to the database. But taking into account the fact that the user can select fields in any order, it was decided to make one event for all fields and send all the data from all fields, and then check on the server which empty ones came with the data. This is where advice is needed, if there are 7 fields, then there are a lot of options for which data will come empty and which not.
And with the usual if check, you get a lot of code.
The question is, is there an option how to make a request to the database even if the variable is empty, i.e. data came with an empty field, or how to make a check so as not to write all the options that are possible.
For example:

var1 = request.GET.get('var1', None)
var2 = request.GET.get('var2', None)
var3 = request.GET.get('var3', None)
if var1 and var2 and var3:
    snippets = Model.objects.filter(pole1=var1, pole2=var2, pole3=var3)
elif var1 and var2 and not var3:
    snippets = Model.objects.filter(pole1=var1, pole2=var2)
elif var1 and not var2 and not var3:
    snippets = Model.objects.filter(pole1=var1)

And so on, how to avoid this option?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Astrohas, 2017-08-15
@Astrohas

filters = {
  "pole1": znach1;
  "pole2":znach2
}
for key in filters.keys():
   if not filters[key]:
      filters.pop(key)
snippets = Model.objects.filter(**filters)

something like this. Of course, you can write shorter and easier, but ... laziness

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question