Skip to content
Advertisement

How to add column in ManyToMany Table (Django)

From the example of Django Book, I understand if I create models as following:

from xxx import B

class A(models.Model):
    b = ManyToManyField(B)

The Django would create a new table(A_B) beyond Table A, which has three columns:

  • id
  • a_id
  • b_id

But now I want to add a new column in the Table A_B, thus would be very easy if I use normal SQL, but now anyone can help me how to do? I can’t find any useful information in this book.

Advertisement

Answer

It’s very easy using django too! You can use through to define your own manytomany intermediary tables

Documentation provides an example addressing your issue:

Extra fields on many-to-many relationships

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement