2011-12-14 9 views
15

jestem konstruowaniu niektórych zapytań filtrujących Django dynamicznie, using this example:Konstruowanie zapytań Django filtry dynamicznie args i kwargs

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

ja po prostu nie wiem, jak budować pozycję na args. Że mam tej tablicy:

strings = ['Foo', 'Bar'] 

Jak mogę dostać stamtąd do:

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

Najbliżej mogę dostać to:

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

Ale ja nie wiem jak skonfiguruj stan |.

Odpowiedz

12

Można iteracyjne go bezpośrednio przy użyciu formatu kwarg (nie wiem właściwego terminu)

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! 

to będzie wyglądać na każdej struny w swojej query_string w każdej dziedzinie w fields i OR wynikiem

Chciałbym mieć moje oryginalne źródło tego, ale to jest dostosowane z kodu, którego używam.

+0

na marginesie, 'reduce' jest teraz' functools.reduce' w Pythonie 3 https://docs.python.org/3.0/library/ functools.html # functools.reduce – wasabigeek

12

masz listę obiektów klasy 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 
Powiązane problemy