Home > Mobile >  Many-to-many relationship with self table Django
Many-to-many relationship with self table Django

Time:09-22

I am having a table with a self-referencing column with many-to-many relations

class PanelUser(core_models.TimestampedModel):
    assigned = models.ManyToManyField("self", related_name="panelusers", blank=True)

    def __str__(self):
        return self.user.username

Problem I have three records A, B, C and if I and assigning A = B then is automatically assigned B = A

I don't understand why this is happing, how I fix it.

CodePudding user response:

A ManyToManyField takes a symmetrical parameter when using "self", when set to False it prevents the behaviour you describe and makes the relationship asymmetrical

assigned = models.ManyToManyField(
    "self",
    related_name="panelusers",
    blank=True,
    symmetrical=False
)
  • Related