Django Many-to-Many (m2m) Relation to same model Django Many-to-Many (m2m) Relation to same model python python

Django Many-to-Many (m2m) Relation to same model


Technically, I'm pretty sure "MyUser" or "self" will work, as long as it's a string in either case. You just can't pass MyUser, the actual class.

However, the docs always use "self". Using "self" is not only more explicit about what's actually happening, but it's impervious to class name changes. For example, if you later changed MyUser to SomethingElse, you would then need to update any reference to "MyUser" as well. The problem is that since it's a string, your IDE will not alert you to the error, so there's a greater chance of your missing it. Using "self" will work no matter what the class' name is now or in the future.


class MyUser(models.Model):    ...    blocked_users = models.ManyToManyField("self", blank=True)


Don't forget use symmetrical=False, if you use .clear() or .add() method for related objects and don't wanna object on other side of relation update own data in relation field.

some_field = models.ManyToManyField('self', symmetrical=False)