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:
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.
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.
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.
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)
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With