Answer the question
In order to leave comments, you need to log in
Django: How to organize a selection according to the data from the form?
There is a form through which a GET request is sent.
It is necessary to make a selection from the database according to the received parameters.
list_of_drives = Drive.objects.filter(manufacturer=request.GET.get('manufacturer', ''),
kind=request.GET.get('kind', ''),
size__gte=int(request.GET.get('min_mem', 0)),
size__lte=int(request.GET.get('max_mem', 0)),
interface=request.GET.get('interface', ''),
ff=request.GET.get('ff', ''),
price__gte=int(request.GET.get('min_price', 0)),
price__lte=int(request.GET.get('max_price', 0)))
Answer the question
In order to leave comments, you need to log in
mapping = {
'manufacturer': ('manufacturer', None),
'kind': ('kind', None),
'min_mem': ('size__gte', int),
'max_mem': ('size_lte', int),
'interface': ('interface', None),
'ff': ('ff', None),
'min_price': ('price__gte', int),
'max_price': ('price__lte', int)
}
list_of_drives = Drive.objects.all()
for k, v in mapping.items(): # iteritems() если Python2
if k in request.GET:
value = request.GET[k]
if callable(v[1]):
value = v[1](value)
list_of_drives = list_of_drives.filter(**{v[0]: value})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question