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
This works (isn’t inefficient) because Querysets are lazy.