django条件过滤器OR

时间:2011-09-25 10:43:02

标签: django

if w:
    conditions['is_discount_table'] = 'Q( is_discount_table = True )'
    conditions['is_discount_banquet'] = 'Q( is_discount_banquet = True )'

pl = Place.objects.filter( **conditions ).order_by( 'name' )

SQL WHERE看起来像是

WHERE (
    "places_place"."is_discount_banquet" = true AND 
    "places_place"."is_discount_table" = true 
)

如何修改SQL WHERE看起来像

w条件
WHERE (

        "places_place"."is_discount_banquet" = true OR
        "places_place"."is_discount_table" = true 

    )

等同于

Place.objects.filter( Q( is_discount_table = True ) | Q( is_discount_banquet = True ) )

3 个答案:

答案 0 :(得分:3)

我找到了答案:

conditions_unnamed = list()
conditions_named = dict( )
if type:
    conditions_named['types__id__in'] = list_unique( type.split( '-' ) )
if w:
    conditions_unnamed.append( Q( is_discount_table = True ) | Q( is_discount_banquet = True ) )
pl = Place.objects.filter( *conditions_unnamed, **conditions_named ).order_by( 'name' )

如果有人知道更好的解决方案,请分享。

答案 1 :(得分:0)

您似乎添加了一些额外的逻辑。我想这就是你想要表达的:

pl = Place.objects.all()
if type:
    pl = pl.filter(types__id__in=type.split( '-' ))
if w:
    pl = pl.filter( Q( is_discount_table = True ) | Q( is_discount_banquet = True ) )
pl = pl.order_by( 'name' )

答案 2 :(得分:0)

queres = {Q()}
...
if ...
queres.update({Q(deprecation_date__lte=datetime.date.today())})
if ...
queres.update({Q(deprecation_date=None)})
...
devices = Device.objects.filter(*queres)