Ashish Kumar Verma
Ashish Kumar Verma

Reputation: 9

ManyToMany Field Refere to Itself

How can make my model so that its ManyToMany Refer to User

class User(AbstractUser):
    teacher_or_student = models.CharField(max_length=100)
    mobile_number = models.CharField(max_length=100)
    grade = models.CharField(max_length=100)
    laptop_yes_or = models.CharField(max_length=100)
    students = models.ManyToManyField(User)

Upvotes: 0

Views: 49

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

You can pass the 'self' string for this. By default a ManyToManyField that refers to itself, is als symmetrical, so you probably want to turn that off, since if a is a student of b, then b is not per se a student of a. You can do that by specifying symmetrical=False [Django-doc]:

class User(AbstractUser):
    teacher_or_student = models.CharField(max_length=100)
    mobile_number = models.CharField(max_length=100)
    grade = models.CharField(max_length=100)
    laptop_yes_or = models.CharField(max_length=100)
    students = models.ManyToManyField(
        'self',
        symmetrical=False,
        related_name='teachers'
    )

Upvotes: 1

Related Questions