Django,在多对多的关系内部self class,我如何在ORM方面相互引用?
Django, in many to many relationship within the self class, how do I reference each other in terms of ORM?
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)
在我的模型 User 中,用户可以相互关注和关注。
我可以通过这个找到用户关注的人:
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
的关系是非对称的。
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)
在我的模型 User 中,用户可以相互关注和关注。
我可以通过这个找到用户关注的人:
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
的关系是非对称的。