python - 如何在Django中实现followers/following

标签 python django django-orm

我想在我的 Django 应用程序中实现关注者/关注功能。

我为每个 User (django.contrib.auth.User) 都有一个 UserProfile 类:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique = True, related_name = 'user')
    follows = models.ManyToManyField("self", related_name = 'follows')

所以我尝试在 python shell 中执行此操作:

>>> user_1 = User.objects.get(pk = 1) # <-- mark
>>> user_2 = User.objects.get(pk = 2) # <-- john
>>> user_1.get_profile().follows.add(user_2.get_profile())
>>> user_1.get_profile().follows.all()
[<UserProfile: john>]
>>> user_2.get_profile().follows.all()
[<UserProfile: mark>]

但如您所见,当我将新用户添加到用户的 follows 字段时,也会在另一侧添加对称关系。从字面上看:如果用户 1 关注用户 2,则用户 2 也关注用户 1,这是错误的

我哪里错了?您有实现关注者并正确关注的方法吗?

谢谢你们。

最佳答案

设置symmetrical在你的 Many2Many 关系中为 False:

follows = models.ManyToManyField('self', related_name='follows', symmetrical=False)

关于python - 如何在Django中实现followers/following,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6218175/

相关文章:

python - Django ORM - 如何在具有多对多字段的两个条件下加入

python - Django 复制/粘贴查询集

python - 打印带有空格的十六进制

python - 使用字典从字符串中检索字典列表

python - Feedparser 停止工作

django - 如何使用 django-cumulus 提供静态文件?

python - 如果用户没有用户名或其他内容,返回给 django admin 的内容

python - 使用 ElasticBeanstalk 在 AWS 上部署在 Python 3.6 上运行的 Django 项目

python - 每个文件合并后添加断行

python - Django ORM : customize a ListView, 并向其查询集添加更多信息