I have a django model, lets say:
class Person(models.Model):
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
And, exists a search form, where I can search rows whether by first_name, by last_name or by both. I have noted that I can link filters in a django queryset, e.g:
def search(request):
list = Person.objects.filter(first_name= val1).filter(last_name=val2)
But what if one of the values val1, val2 is null? Should I do something like:
def searh(request):
if val1 != null and val2 == null:
list = Person.objects.filter(first_name= val1)
if val2 == null and val2 != null:
list = Person.objects.filter(last_name= val2)
if val2 != null and val2 != null:
list = Person.objects.filter(first_name= val1).filter(last_name=val2)
Is there any direct way to do this?
thanks in advance
def search(request, val1, val2):
persons = Person.objects.all()
if val1:
persons = persons.filter(first_name=val1)
if val2:
persons = persons.filter(last_name=val2)
return persons
This works (isn't inefficient) because Querysets are lazy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With