Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional nested filters in Django

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

like image 852
Cheluis Avatar asked Mar 20 '26 05:03

Cheluis


1 Answers

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.

like image 71
tback Avatar answered Mar 22 '26 05:03

tback