2011-10-03 106 views
0

請告訴我如何使這個查詢動態:創建一個動態查詢

products = category.product_set.filter(Q(feature__value__value='Red') 
|Q(feature__value__value='Blue'), feature__name__name='Color') 

我需要顯示所有的顏色紅色和藍色的產品。

並請告訴我如何更好地做到這一點查詢:

產品全部用紅色和藍色,但與選項-1。我的理解是正確的?:

products = category.product_set.filter(Q(feature__value__value='Red') 
|Q(feature__value__value='Blue'), feature__name__name='Color').filter(Q(feature__value__value='Yes') 
|Q(feature__value__value='No', feature__name__name='Option-1') 

回答

0

我想你要找的東西是這樣的:

# create a dynamic set of keywords 
kwargs = {} 
name = 'Color' 
# since you're looking for literals, I would simply use 'in' as the query 
kwargs[name + "__in"] = ['Red','Blue'] 

products = category.product_set.filter(**kwargs) 
+0

非常感謝你:) – user962963

+0

@ user962963如果你喜歡這個答案,你可以將其標記爲接受;-) – cwallenpoole