2

我有一个字典列表,其中包含我从模型中获得app_label的键:modelContentType

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

我需要从中生成一组组合Q对象以用作ForeignKey.limit_choices_to参数。这是我需要的输出:

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使用运算符创建组合对象列表?|

4

1 回答 1

1

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

limit = reduce(operator.or_, (Q(**condition) for condition in model_list))
于 2015-01-13T15:08:48.320 回答