gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:22 25 4
gpt4 key购买 nike

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 个带有标签的产品 Red200cm在组中colorwidth .一种产品带有红色标签,但另一种产品没有分配给组的标签,因此我预计会退回 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!

关于python - Django 查询集如何排除没有组或标签的产品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42580896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com