How to add column in ManyToMany Table (Django)

后端 未结 3 1729
醉酒成梦
醉酒成梦 2020-12-29 03:22

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)
         


        
3条回答
  •  再見小時候
    2020-12-29 03:51

    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'
    

提交回复
热议问题