【问题标题】:Django annotate existance in related fieldDjango注释相关领域的存在
【发布时间】:2021-03-29 15:43:16
【问题描述】:

我的模型:

class Character(models.Model):
    name = models.CharField(max_length=100)

class Item(models.Model):
    name = models.CharField(max_length=100)

class Equipment(models.Model):
    owner = models.ForeignKey(Character, on_delete = models.CASCADE)
    item = models.ForeignKey(Item, on_delete = models.RESTRICT)

现在我需要注释物品是否在设备中:

 you = Character.objects.get(pk=1)
 items = Item.objects.all().annotate(ready=Value(True, output_field=models.BooleanField()), filter=Q(equipment__owner__in=you))

但有些不对劲:

TypeError: 'Character' object is not iterable

【问题讨论】:

    标签: django django-annotate


    【解决方案1】:

    您尝试注释并拥有此filter=Q(equipment__owner__in=you)。问题是youCharacter 的一个实例@ 不是字符的可迭代所以它应该是filter=Q(equipment__owner=you)。这仍然是不正确的,因为您不能以这种方式在注释中进行过滤。

    要注释相关字段的存在,请使用Exists() subqueries [Django docs]

    from django.db.models import Exists, OuterRef
    
    you = Character.objects.get(pk=1)
    equipments = Equipment.objects.filter(item=OuterRef('pk'), owner=you)
    Item.objects.annotate(ready=Exists(equipments))
    

    【讨论】:

    • @Abdul_Aziz_Barkat 我不喜欢它,但它有效。 :)
    猜你喜欢
    • 2015-08-12
    • 1970-01-01
    • 2015-03-24
    • 2021-07-26
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多