Django,在自类中的多对多关系中,如何在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)
在我的模型用户"中,用户可以彼此跟随.
In my model, User, users can follow and followed by each other.
我可以由此找到用户关注的人
I can find who the user is following by this:
user1 = User.objects.get(id=1)
following = user1.following.all()
但是,我不知道如何找到用户的关注对象.
However, I can't figure out how to find whom the user is followed by.
我尝试过:
user1.followers.all()
因为它是我模型中以下字段中的related_name.
since it is the related_name in the following field in my model.
有人可以教我该怎么做吗?
Can anybody please teach me how to do this?
非常感谢您.
推荐答案
您应传递从文档中
当Django处理此模型时,它会确定自己具有一个
ManyToManyField
,因此,它不会向User
类添加followers
属性.相反,假定ManyToManyField
是对称的–也就是说,如果我是您的follower
,那么您就是我的follower
.
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
.
如果不想与self
建立多对多关系,请将symmetrical
设置为False
.这将迫使Django为反向关系添加描述符,从而允许ManyToManyField
关系是非对称的.
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
中,您都可以访问以下内容:
Then in your views.py
you can access both:
following = user.following.all()
followers = user.followers.all()
自从现在以来,与self
的关系是不对称的.
Since now the relationship with self
is non-symmetrical.
这篇关于Django,在自类中的多对多关系中,如何在ORM方面互相引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!