Django: Query using contains each value in a list

2019-01-06 10:27发布

问题:

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'])

回答1:

reduce(operator.and_, (Q(first_name__contains=x) for x in ['x', 'y', 'z']))


回答2:

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)


回答3:

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.



回答4:

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