如何在ManyToMany表(Django)中添加列?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (32)

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

Django将创建一个新表(A_(B)表A以外有三栏:

id

  • a_id
  • b_id

但是现在我想在表A中添加一个新列_B,所以如果我使用普通SQL会很容易,但是现在任何人都可以帮我做什么?我在这本书里找不到任何有用的信息。

提问于
用户回答回答于

使用Django也很容易!你可以用through定义自己的多个中间表

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)
用户回答回答于

使用Django 1.8和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'

扫码关注云+社区