2011-12-14 14 views
15

sto costruendo alcune query di filtro Django in modo dinamico, using this example:Costruire filtro query Django in modo dinamico con args e kwargs

kwargs = { 'deleted_datetime__isnull': True } 
args = (Q(title__icontains = 'Foo') | Q(title__icontains = 'Bar')) 
entries = Entry.objects.filter(*args, **kwargs) 

io non sono solo sicuro di come costruire la voce per args. Dire che ho questa matrice:

strings = ['Foo', 'Bar'] 

Come faccio ad arrivare da lì:

args = (Q(title__icontains = 'Foo') | Q(title__icontains = 'Bar') 

Il più vicino che può ottenere è:

for s in strings: 
    q_construct = Q(title__icontains = %s) % s 
    args.append(s) 

Ma non so come impostare la condizione |.

risposta

12

È possibile scorrere direttamente utilizzando un formato kwarg (non so il termine corretto)

argument_list = [] #keep this blank, just decalring it for later 
fields = ('title') #any fields in your model you'd like to search against 
query_string = 'Foo Bar' #search terms, you'll probably populate this from some source 

for query in query_string.split(' '): #breaks query_string into 'Foo' and 'Bar' 
    for field in fields: 
     argument_list.append(Q(**{field+'__icontains':query_object})) 

query = Entry.objects.filter(reduce(operator.or_, argument_list)) 

# --UPDATE-- here's an args example for completeness 

order = ['publish_date','title'] #create a list, possibly from GET or POST data 
ordered_query = query.order_by(*orders()) # Yay, you're ordered now! 

Questo cercherà per ogni stringa nel vostro query_string in ogni campo in fields e OR il risultato

Vorrei avere ancora la mia fonte originale per questo, ma questo è adattato dal codice che uso.

+0

su un lato nota, 'reduce' è ora' functools.reduce' in Python 3 https://docs.python.org/3.0/library/ functools.html # functools.reduce – wasabigeek

12

avete elenco di oggetti di classe Q,

args_list = [Q1,Q2,Q3] # Q1 = Q(title__icontains='Foo') or Q1 = Q(**{'title':'value'}) 
args = Q() #defining args as empty Q class object to handle empty args_list 
for each_args in args_list : 
    args = args | each_args 

query_set= query_set.filter(*(args,)) # will excute, query_set.filter(Q1 | Q2 | Q3) 
# comma , in last after args is mandatory to pass as args here 
Problemi correlati