How to add column to ManyToMany table (Django)

From the Django Book example, I understand that I create models as follows:

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

Django will create a new table (A_B) outside of table A, which has three columns:

  • ID
  • a_id
  • b_id

But now I want to add a new column to table A_B, so it would be very easy if I used plain SQL, but now can anyone help me how to do this? I can not find useful information in this book.

+17
python django many-to-many
Sep 24 '12 at 14:33
source share
2 answers

It is very simple using django! You can use through to define your own custom staging tables

The documentation contains an example of a solution to your problem:

 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) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) 
+43
Sep 24
source share
— -

Under the hood, Django automatically creates an end-to-end model. You can change these column names of the foreign key in the automatic model.

I could not check the consequences for all the scenarios until it worked correctly for me.

Using Django 1.8 onwards _ meta api :

 class Person(models.Model): pass class Group(models.Model): members = models.ManyToManyField(Person) Group.members.through._meta.get_field('person').column = 'alt_person_id' Group.members.through._meta.get_field('group' ).column = 'alt_group_id' # Prior to python 1.8 _meta can also be used, but is more hackish than this Group.members.through.person.field.column = 'alt_person_id' Group.members.through.group .field.column = 'alt_group_id' 
+1
Sep 16 '16 at 7:39
source share



All Articles