如何在Django中实现关注者/关注者 [英] How to implement followers/following in Django

查看:174
本文介绍了如何在Django中实现关注者/关注者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to implement the followers/following feature in my Django application.

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

I've an UserProfile class for every User (django.contrib.auth.User):

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

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

So I tried to do this in 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>]

但是正如您所看到的,当我将新用户添加到用户的后续活动字段时,另一侧也会添加对称关系。从字面上看:如果user1跟随user2,则user2也跟随user1,这是错误

But as you can see, when I add a new user to the follows field of a user, is also added the symmetrical relation on the other side. Literally: if user1 follows user2, also user2 follows user1, and this is wrong.

我的错误在哪里?

谢谢你们。

推荐答案

symmetric 设置为False在Many2Many关系中:

Set symmetrical to False in your Many2Many relation:

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

这篇关于如何在Django中实现关注者/关注者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆