首页 > 解决方案 > Django遗留数据库迁移多对多中间表

问题描述

旧版数据库迁移到 Django (v1.11)(来自 Sequelize)。

数据库中的中间表没有 id(主键属性),因为 Sequelize 不需要它,但在 Django 中似乎是强制性的。

当前的 Django 设置:

class Address(models.Model):
    keyword = models.CharField(max_length=255)
    city = models.CharField(max_length=255, blank=True, null=True)
    state = models.CharField(max_length=255, blank=True, null=True)
    createdAt = models.DateTimeField(db_column='createdAt', auto_now_add=True)
    updatedAt = models.DateTimeField(db_column='updatedAt', auto_now=True)

    class Meta:
        db_table = 'Addresses'

class CustomerExecutive(models.Model):
    name = models.CharField(max_length=255, blank=True, null=True)
    email = models.CharField(max_length=255)
    addresses = models.ManyToManyField('Address', through='AddressCustomerExecutiveMapping')
createdAt = models.DateTimeField(db_column='createdAt', auto_now_add=True)
updatedAt = models.DateTimeField(db_column='updatedAt', auto_now=True)

    class Meta:
        db_table = 'CustomerExecutives'

class AddressCustomerExecutiveMapping(models.Model):
    address = models.ForeignKey(Address,  db_column='addressId', primary_key=True)
    customer_executive = models.ForeignKey(CustomerExecutive, db_column='customerExecutiveId', primary_key=True)
    createdAt = models.DateTimeField(db_column='createdAt', auto_now_add=True)
    updatedAt = models.DateTimeField(db_column='updatedAt', auto_now=True)

    class Meta:
        db_table = 'AddressCustomerExecutiveMapping'
    unique_together = (('address', 'customer_executive'),)

如果primary_key未指定,AddressCustomerExecutiveMapping.address或者AddressCustomerExecutiveMapping.customer_executive它给出了所需的主键错误,并且如果指定,我无法在列中添加重复值(那时不是多对多)。

我该如何解决这个问题?

标签: djangosequelize.jsdatabase-migration

解决方案


推荐阅读