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 afollowers
attribute to theUser
class. Instead, theManyToManyField
is assumed to be symmetrical – that is, if I am yourfollower
, then you are myfollower
.If you do not want symmetry in many-to-many relationships with
self
, setsymmetrical
toFalse
. This will force Django to add the descriptor for the reverse relationship, allowingManyToManyField
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/