问题
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