A
A
Aidar5672021-09-16 19:25:24
Django
Aidar567, 2021-09-16 19:25:24

Filtering a model by a limited but dynamic number of parameters in a get request?

Tell the Django view logic to filter the model by several possible parameters from the get request. Type the client can filter only on one field, and can on all. It can be by date period and at the same time select only the beginning / from and not select by, with the same price. I can't figure out how to keep track of all this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gimntut, 2021-09-17
@gimntut

If it is very rough, then something like this:

# ... Где-то здесь определяем quryset как нефильтрованный набор
title = request.GET.get('title')
price_min = request.GET.get('price_min')
price_max = request.GET.get('price_max')
if title:
  quryset = quryset.filter(title=title)
if price_min and price_max:
  quryset = quryset.filter(price__range=(price_min, price_max))
elif price_min:
  quryset = quryset.filter(price__gte=price_min)
elif price_max:
  quryset = quryset.filter(price__lt=price_max)

The main thing is not to forget
quryset =
and not to write if instead of elif for paired parameters, such as price_min, price_max, and then everything will work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question