Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Query using contains each value in a list

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']) 
like image 552
neolaser Avatar asked Jan 28 '11 04:01

neolaser


People also ask

How can I filter a Django query with a list of values?

To filter a Python Django query with a list of values, we can use the filter method with in . to search Blog entries with pk set to 1,4 or 7 by calling Blog. objects. filter with the pk_in argument set to [1, 4, 7] .

What is Select_related in Django?

Using select_related() Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects.

What is objects all () Django?

The Manager is the main source of QuerySets for a model. For example, Blog.objects.all() returns a QuerySet that contains all Blog objects in the database.


1 Answers

import operator from django.db.models import Q  User.objects.filter(reduce(operator.and_, (Q(first_name__contains=x) for x in ['x', 'y', 'z']))) 

for python 3

from functools import reduce 

.

like image 162
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 12:09

Ignacio Vazquez-Abrams