A
A
Anton2015-12-03 23:30:34
Django
Anton, 2015-12-03 23:30:34

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)))

This code will only work if all fields are filled. And what is the best way to check for emptiness with the subsequent formation of the correct filter?
Is there a smarter and prettier option than going through each field in an if...else , checking and applying filtering in each branch?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-12-04
@Gambetto

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})

Don't forget to wrap it in try, because any nonsense can come to request.GET.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question