How to implement followers/following in Django

谁都会走 提交于 2019-12-03 03:20:05

问题


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

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')

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>]

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.

Where's my mistake? Have you a way for implement followers and following correctly?

Thank you guys.


回答1:


Set symmetrical to False in your Many2Many relation:

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



回答2:


In addition to mouad's answer, may I suggest choosing a different *related_name*: If Mark follows John, then Mark is one of John's followers, right?



来源:https://stackoverflow.com/questions/6218175/how-to-implement-followers-following-in-django

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