我有一个字典列表,其中app_label
和model
键来自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
运算符创建合并|
对象的列表?
答案 0 :(得分:1)
将reduce
与operator.or_
(或lambda a, b: a | b
)一起使用:
limit = reduce(operator.or_, (Q(**condition) for condition in model_list))