I need to perform a django query that checks if a field contains all values within a list. The list will be of varying length
Example
User.objects.filter(first_name__contains=['x','y','z'])
I need to perform a django query that checks if a field contains all values within a list. The list will be of varying length
Example
User.objects.filter(first_name__contains=['x','y','z'])
reduce(operator.and_, (Q(first_name__contains=x) for x in ['x', 'y', 'z']))
import operator
from django.db.models import Q
q = ['x', 'y', 'z']
query = reduce(operator.and_, (Q(first_name__contains = item) for item in ['x', 'y', 'z']))
result = User.objects.filter(query)
Just another approach.
qs = User.objects.all()
for search_term in ['x', 'y', 'z']:
qs = qs.filter(first_name__contains=search_term)
I'm not sure if it is better, but it's more readable.
from django.db.models import Q
User.objects.filter(Q(first_name__contains=x)&Q(first_name__contains=y)&Q(first_name__contains=z))
Works for me on Django 1.8 python 2.7
doc => https://docs.djangoproject.com/en/1.8/ref/models/querysets/#q-objects
for more recent => https://docs.djangoproject.com/en/2.1/ref/models/querysets/#q-objects