gpt4 book ai didi

Django,在 self 类内的多对多关系中,我如何在ORM方面相互引用?

转载 作者:行者123 更新时间:2023-12-02 02:47:49 25 4
gpt4 key购买 nike

class User(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
gender = models.IntegerField()
email = models.CharField(max_length=100)
password = models.CharField(max_length=255)
following = models.ManyToManyField("self", related_name='followers')
objects = UserManager()
def __repr__(self):
return "User: {0}".format(self.name)

在我的模型“用户”中,用户可以关注并相互关注。

我可以通过以下方式找到用户正在关注的人:

user1 = User.objects.get(id=1)
following = user1.following.all()

但是,我不知道如何找到用户关注的人。

我尝试过:

user1.followers.all()

因为它是我的模型中以下字段中的 related_name。

有人可以教我如何做到这一点吗?

非常感谢。

最佳答案

您应该通过symmetrical属性为 False

来自文档:

When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn’t add a followers attribute to the User class. Instead, the ManyToManyField is assumed to be symmetrical – that is, if I am your follower, then you are my follower.

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.

就您而言:

class User(models.Model):
# ...
following = models.ManyToManyField('self', related_name='followers', symmetrical=False)
# ...

然后在您的 views.py 中您可以访问两者:

following = user.following.all()
followers = user.followers.all()

现在与self的关系是非对称的。

关于Django,在 self 类内的多对多关系中,我如何在ORM方面相互引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45847930/

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