Fred Collins
Fred Collins

Reputation: 5010

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.

Upvotes: 19

Views: 9461

Answers (2)

mouad
mouad

Reputation: 70031

Set symmetrical to False in your Many2Many relation:

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

Upvotes: 29

XORcist
XORcist

Reputation: 4367

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?

Upvotes: 17

Related Questions