Django.filter on the same option with multiple capabilities

I have an object model. I also have a list of options for filtering the results. I'm not sure if there is an easy way to filter objects in the model so that any object that matches any of the elements in the filter list is returned. For instance:

# returns all users with name starting with 'P'
usersWithPName = User.objects.filter(name__startswith = 'P')
# 3 letters to filter User model with
filterList = ['P', 'T', 'R'] 
# ideally would return all users with name starting with either 'P', 'T', or 'R'
usersWithPTRName = User.objects.filter(name__startswith = filterList) 

Is there a way to filter (in this case) the User model so that it returns an object that matches any of the elements in the filter list?

+5
source share
2 answers

This can be done using Q objects.

from django.db.models import Q
usersWithPTRName = User.objects.filter(Q(name__startswith='P') |
                                       Q(name__startswith='T') |
                                       Q(name__startswith='R')) 

You can also create Q filters at runtime:

filterList = ['P', 'T', 'R']
query = Q()
for letter in filterList:
    query = query | Q(name__startswith=letter)
usersWithPTRName = User.objects.filter(query)
+17
source

Two options.

  • .

  • .

class User( models.Model ):
    ... all the usual stuff ...
    @property
    def first_letter( self ):
        return self.name[:1]

filter( first_letter__in=('P','T','R') )

Django Q .

: https://stackoverflow.com/search?q=django+Q+objects

0

All Articles