How to implement followers/following in Django

Fred Collins picture Fred Collins · Jun 2, 2011 · Viewed 8k times · Source

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.

Answer

mouad picture mouad · Jun 2, 2011

Set symmetrical to False in your Many2Many relation:

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