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

标签 django django-models orm many-to-many m2m

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/

相关文章:

django - 从Django评论框架以相反的顺序重新排列评论

python - django 测试无法将固定装置的数据插入 mysql

java - JDBC 查询缓存和预缓存

php - Magento 1.9 使用 SQL(MySQL) 创建类别和产品

django - 如何在 docker 上从 ascii postgresql 数据库切换到 utf8?

python - 我在哪里可以下载 Django 文档?

python - 更改 Django/Postgres db_table 名称

django - 使用django修改 View 中的对象值而不修改数据库值

python - 如何在django中使用数组

c# - 流利的 Nhibernate,处理一对多关系