gpt4 book ai didi

Django,查询集返回许多 self

转载 作者:行者123 更新时间:2023-12-01 09:38:21 25 4
gpt4 key购买 nike

遵循常规的多对多查询集逻辑会给我错误。我想因为它与 self 有关,我可能需要做一些额外的魔法,但我不知道是什么魔法。

型号:

class Entry(models.Model):
title = models.CharField(max_length=100, verbose_name='title')
related = models.ManyToManyField('self', related_name='related_entries', blank=True)

查询集:

entry = Entry.objects.get(pk=1)
related = entry.related_entries.all()

错误:'Entry' 对象没有属性 'related_entries'

最佳答案

查看 symmetrical 的文档ManyToManyField 的参数:

When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn't add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical -- that is, if I am your friend, then you are my friend.

If you do not want symmetry in many-to-many relationships with self, set symmetrical to False. This will force Django to add the descriptor for the reverse relationship, allowing ManyToManyField relationships to be non-symmetrical.

所以,为了使用 related_name,设置 symmetrical=False

关于Django,查询集返回许多 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3953034/

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