Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 972
Wei Lin Avatar asked Sep 24 '12 14:09

Wei Lin


People also ask

How do you use many to many fields?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.

What is through in Django models?

The through attribute/field is the way you customize the intermediary table, the one that Django creates itself, that one is what the through field is changing.


2 Answers

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) 
like image 200
dm03514 Avatar answered Sep 29 '22 08:09

dm03514


Under the hood, Django creates automatically a through model. It is possible to modify this automatic model foreign key column names.

I could not test the implications on all scenarios, so far it works properly for me.

Using Django 1.8 and 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 Django 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' 
like image 41
ajaest Avatar answered Sep 29 '22 09:09

ajaest