Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement followers/following in Django

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.

like image 486
Fred Collins Avatar asked Jun 02 '11 17:06

Fred Collins


2 Answers

Set symmetrical to False in your Many2Many relation:

follows = models.ManyToManyField('self', related_name='follows', symmetrical=False)
like image 108
mouad Avatar answered Nov 19 '22 17:11

mouad


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?

like image 31
XORcist Avatar answered Nov 19 '22 19:11

XORcist