Django .filter on same option with multiple possibilities

You can use python reduce and operator builtins:

import operator
from functools import reduce

from django.db.models import Q

values = ["blue", "green", "brown"]

# or condition
conditions = reduce(operator.or_, [Q(**{"categories__slug": value}) for value in values])

# and condition
conditions = reduce(operator.and_, [Q(**{"categories__slug": value}) for value in values])

queryset = queryset.filter(conditions)

This can be done with Q objects

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

Also you can build 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)

Tags:

Django

Filter