eso
eso

Reputation: 103

Django Post or None

I am trying to query with multiple filters or none

technician = request.POST.get('technician')
## in the previous screen the user may not have informed the parameter, it should not be required

uniorg = request.POST.get('uniorg')
## in the previous screen the user may not have informed the parameter, it should not be required

calls = Call.objects.filter(
    technician=technician,
    uniorg=uniorg,
    ...)

I tried:

technician = request.POST.get('technician', '')

and

technician = request.POST.get('technician' or None)

Not all parameters are required. Someone can help me?

Upvotes: 1

Views: 678

Answers (4)

eso
eso

Reputation: 103

Final code

list_filters = ['type', 'technician', 'ended', 'uniorg']
filters = {k: v for k, v in request.POST.items() if k in list_filters}

    for l in list_filters:
        if request.POST[l] == '0' or request.POST[l] == '':
            del filters[l]
    calls = Call.objects.filter(start_time__gte=start_date, start_time__lte=end_date, **filters)

Upvotes: 1

aliva
aliva

Reputation: 5740

Have you tried django-filter? it's really good tool for providing filter by GET parameters (note that I have no idea about your data base design so this code might not work)

# filters.py
class CallFilter(django_filters.FilterSet):
    class Meta:
        model = Call
        fields = ['technician', 'uniorg',]

# view.py
items = CallFilter(request.GET, queryset=Call.objects.all())

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599876

An alternative is to use dictionary parameter expansion:

filters = {k: v for k, v in request.POST.items() if k in ['technician', 'uniorg', ...]}
calls = Call.objects.filter(**filters)

or, if you're sure that only actual valid filter values can be in the POST, pass it directly:

calls = Call.objects.filter(**request.POST)

Upvotes: 0

Ralf
Ralf

Reputation: 16515

You could try something like this:

qs = Call.objects.all()

technician = request.POST.get('technician')
if technician is not None:
    qs = qs.filter(technician=technician)

uniorg = request.POST.get('uniorg')
if uniorg is not None:
    qs = qs.filter(uniorg=uniorg)

Upvotes: 0

Related Questions