Django, in many to many relationship within the self class, how do I reference each other in terms of ORM?

回眸只為那壹抹淺笑 提交于 2019-12-05 20:44:51

You should pass the symmetrical attribute to be False.

From the docs:

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.

In your case:

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

Then in your views.py you can access both:

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

Since now the relationship with self is non-symmetrical.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!