Skip to main content
 首页 » 编程设计

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

2025年05月04日11Leo_wl

我有一个包含 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 对象列表?

请您参考如下方法:

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

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