Conditional nested filters in Django

I have a django model, say:

class Person(models.Model):
   first_name = models.CharField(max_length=25)
   last_name  = models.CharField(max_length=25)

And there is a search form where I can search for strings, be it first_name, last_name, or both. I noticed that I can bind the filters in the django request set, for example:

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?

early

+3
source share
2 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 (inefficiently) because Querysets are lazy .

+6
source

(Disclaimer: tested in Python 2.7, Django 1.6, although it should work at all)

I recently got acquainted with the following construction, which is directly related to the OP problem:

def search(request, val1, val2):
    filter_args={}
    if val1:
        filter_args["first_name"]=val1
    if val2:
        filter_args["last_name"]=val2

    persons = Person.objects.filter(**filter_args)

    return persons

, , a-priori, val1, val2. , (and), , , , .filter(...).filter(...) (or). age , , ( val3 ):

    if val3:
        filter_args["age"]=val3

, , , Django .

+4

All Articles