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

后端 未结 5 809
别跟我提以往
别跟我提以往 2020-12-05 04:17

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):
    ...
             


        
5条回答
  •  庸人自扰
    2020-12-05 04:41

    If you use self or MyUser you will get a NameError in both cases. You should write "self" as string. See the example below:

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

    And do not forget to set the symmetrical attribute to False if the relationship is not symmetrical.

    For further details check: https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ManyToManyField

提交回复
热议问题