创建动态查询

时间:2011-10-03 15:20:23

标签: django

请告诉我如何使这个查询动态:

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

我需要显示所有颜色为红色和蓝色的产品。

请告诉我如何最好地进行此查询:

所有产品都带有红色和蓝色,但带有Option-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')

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是:

# 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)