Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to create a many-to-many relationship from and to a user class object.

I have something like this:

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

The question is if I can use the class reference inside itself. Or do I have to use "self" insead of "MyUser" in the ManyToManyField? Or is there another (and better) way to do it?

like image 901
Ron Avatar asked Jul 30 '12 12:07

Ron


People also ask

How does Django handle many-to-many relationship?

Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it.

How do you add data to many-to-many fields in Django?

To add data into ManyToMany field with Python Django, we can use the add method. This will add the entry for the association table between my_obj and categories .


2 Answers

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.

like image 52
Chris Pratt Avatar answered Oct 02 '22 12:10

Chris Pratt


class MyUser(models.Model):     ...     blocked_users = models.ManyToManyField("self", blank=True) 
like image 36
Goin Avatar answered Oct 02 '22 13:10

Goin