2011-01-28 5 views

risposta

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

grazie per la risposta. Sono ancora insicuro su come usare questo ... – neolaser

+9

'User.objects.filter (reduce (...))' Sta facendo l'equivalente di 'User.objects.filter (Q (first_name__contains = 'x') & Q (first_name__contains = 'y') & Q (first_name__contains = 'z')) ' –

+0

ok bene! grazie Ignacio e Yuji – neolaser

18
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

Hey :). Benvenuti in SO. Mente aggiungendo un po 'di carne alla tua risposta? Normalmente ci piace fornire un po 'più di informazioni di un semplice dump di codice per una risposta, solo per aiutare gli altri utenti a capire meglio cosa sta succedendo :). Grazie ^^ – Patrice

+10

@Patrice potrebbe anche fare lo stesso commento alla risposta scelta, dal ragazzo con 339K rep. Questa risposta ha almeno più contesto. :) – bozdoz

+0

se si utilizza Python 3, usare 'import functools' e usare' functools.reduce'. Vedi [questo] (https://stackoverflow.com/a/10226421/1526703) – Anupam

Problemi correlati