如何从列表中生成组合Q对象?

时间:2015-01-13 15:06:05

标签: python django django-q django-contenttypes

我有一个字典列表,其中app_labelmodel键来自ContentType模型:

model_list = [
    {
        'app_label': 'store',
        'model': 'product',
    },
    {
        'app_label': 'store',
        'model': 'profile',
    },
]

我需要从中生成一组合并Q objects以用作ForeignKey.limit_choices_to argument。这是我需要的输出:

limit = Q(app_label = 'store', model = 'product') | Q(app_label = 'store', model = 'profile')

所以我可以在这样的模型中使用它:

class Review(models.Model):
    content_type = models.ForeignKey(ContentType, limit_choices_to = limit)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    # ...

通过遍历此词典列表,任何人都知道如何使用Q运算符创建合并|对象的列表?

1 个答案:

答案 0 :(得分:1)

reduceoperator.or_(或lambda a, b: a | b)一起使用:

limit = reduce(operator.or_, (Q(**condition) for condition in model_list))