Skip to main content
 首页 » 编程设计

python之Django 查询集如何排除没有组或标签的产品

2024年10月01日26kevingrace

从Group开始,我想返回一个queryset项,但如果组没有分配给它的标签的产品,则从查询集中排除该组。

模型

class Group(models.Model): 
    name = models.CharField(max_length=50) 
 
class Tag(models.Model): 
    name = models.CharField(max_length=50) 
    group = models.ForeignKey('Group', related_name='tags') 
 
class Product(models.Model): 
    name = models.CharField(max_length=50) 
    tags = models.ManyToManyField('Tag', related_name='products') 

这是我试过的:

Group.objects.all().exclude(tags__products__isnull=True) 

以上似乎没有返回正确的结果。如果我有 2 个带有标签的产品 Red和 200cm在组中color和 width .一种产品带有红色标签,但另一种产品没有分配给组的标签,因此我预计会退回 1 组。上面错误地给我我得到0?

另一个例子

Group 1 Color 
Group 2 Width 
 
Tag Red - FK to Group 1 
 
Product 1 FK to tag Red 

结果应该是只显示第 1 组,因为第 2 组没有带标签的产品。

请您参考如下方法:

如果 'color' Group 中有另一个 Tag,则可以解释您描述的行为。如果该标签没有产品,您的 exclude 会因为该标签而正确排除颜色组。你应该反过来处理它:

Group.objects.filter(tags__products__isnull=False)   
# one tag with a product suffices to include the group -> intended! 

代替

Group.objects.exclude(tags__products__isnull=True)   
# one tag WITHOUT a product suffices to exclude the group 
# even if other tags of the group have products -> not intended!