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

How to generate a combined Q object from a list?

我有一个字典列表,其中包含 app_labelmodel 键,这些键是我从 ContentType 模型中获得的:

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

我需要生成一组组合Q objects from this to use as a 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 对象的列表?

使用reduce with operator.or_(或lambda a, b: a | b):

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