Reputation: 53
I have three different search inputs(by the text, by date and a checkbox) is it possible at all to Handle three post requests?E.g. I at first want to find a lesson by text search,then after I found it, I want to search the results by the date. Will something like that work or no?
def my_view(request):
if request.method == "POST":
if request.POST['value_one']:
# Do stuff here
elif request.POST['value_two']:
# Do stuff here
elif request.POST['value_three']:
# Do stuff here
else:
# Do something else
Upvotes: 1
Views: 70
Reputation: 449
What I usually do is pull the values with a default value and then filter.
def my_view(request):
value_one = request.GET.get("value_one", None)
value_two = request.GET.get("value_two", None)
value_three = request.GET.get("value_three", None)
objects = MyModel.objects.all()
if value_one:
objects = objects.filter(field_one=value_one)
if value_two:
objects = objects.filter(field_two=value_two)
if value_three:
objects = objects.filter(field_three=value_three)
# at this point you have a list that is filtered by all
# values that were specified
#
# filter calls are just building the final SQL so at
# no point the database was contacted yet, until you
# start to iterate over the objects variable.
# This way you only ever get the objects you really
# really want into memory.
for obj in objects: # now the database was hit
print(f"Found object with primary key {obj.pk}")
Notice also how I used GET
method instead of POST
. That is a cleaner way to pass filters. POST
should be used for literally posting data to the server, as in creating new entities. The part behind ?
in URL is called query and was made exactly for this purpose. It also allows users to bookmark favourite filters simply by bookmarking the current page, simplifies navigation (no more "This document has expired, do you want to resend the data?" messages). I'm not saying POST
doesn't work, but GET
is cleaner.
Edit: You could totally replace request.GET
with request.POST
if you really wanted to, it would work just the same!
Upvotes: 2