class User(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
gender = models.IntegerField()
email = models.CharField(max_length=100)
password = models.CharField(max_length=255)
following = models.ManyToManyField("self", related_name='followers')
objects = UserManager()
def __repr__(self):
return "User: {0}".format(self.name)
In my model, User, users can follow and followed by each other.
I can find who the user is following by this:
user1 = User.objects.get(id=1)
following = user1.following.all()
However, I can't figure out how to find whom the user is followed by.
I tried:
user1.followers.all()
since it is the related_name in the following field in my model.
Can anybody please teach me how to do this?
Thank you very much.
You should pass the
symmetrical
attribute to beFalse
.From the docs:
In your case:
Then in your
views.py
you can access both:Since now the relationship with
self
is non-symmetrical.