Search code examples
pythondjangodjango-modelsmany-to-many

Django self referential m2m field causes causes missing attribtue error


I get an error if I try to make a self-referential m2m Field. Am I missing something here?

class UserProfile(models.Model):
    following = models.ManyToManyField('self', related_name='followers')

somewhere else in a serializer:

def get_followers(user):
    return user.profile.followers

AttributeError: 'UserProfile' object has no attribute 'followers'

Is there another way I can implement followers? Maybe I should make another model to do this or use a library?


Solution

  • By default, Django treats all self m2m relations as symmetrical, for example if I am your friend, you are my friend too. When relation is symmetrical, Django won't create reverse relation attribute to your model.

    If you want to define non-symmetrical relation, set symmetrical=False attribute on your field, example:

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

    More on that in Django documentation