M
M
mr_forlife2021-02-28 11:16:59
Django
mr_forlife, 2021-02-28 11:16:59

How to implement search (filtering) with multiple parameters in Django?

The model has several fields. How can you implement search (filtering) of data on a site with an arbitrary set of filters? For example, the model has fields: field_1, field_2, field_3. The user, using the search form on the site, fills in field_1 and field_3, and field_2 remains empty. Each form field corresponds to one field in the model. Because one of the fields is not filled, then the construction model.objects.filter(filter_1, filter_2, filter_3)
cannot be used.
Each filter must complement the others, i.e. work according to the AND principle, but correctly process empty fields.
Due to inexperience, the use of if ... else comes to mind, but I consider this approach not rational, because with each added field, the code will grow very large and the probability of errors will increase greatly.
Surely, in such a complex and thoughtful system as Django, something has already been invented for an essentially standard task. I've been googling for two days now, but I can't find anything useful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-02-28
@mr_forlife

How to make a dynamic number of Q requests?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question