Django迁移时如何设置/提供默认值?

JPG格式

场景
我有一个模特,Customer

class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.CharField(max_length=100)


现在,我通过以下关系更新了company属性ForeignKey

class Company(models.Model):
    name = models.CharField(max_length=100)
    location = models.CharField(max_length=100)


class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.ForeignKey(Company)



我需要的是,当新的迁移应用于数据库时,相应的Company实例必须自动生成并映射到实例company属性Customer

那可能吗?我该如何实现?

安托万·平沙德

让我们从原始模型开始,逐步进行。

class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.CharField(max_length=100)

首先,您必须保留原始字段并创建一个新字段,然后才能还原旧数据。

class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.CharField(max_length=100)
    _company = models.ForeignKey(Company)

现在,您可以使用创建第一次迁移manage.py makemigrations然后,您将必须创建数据迁移使用创建迁移manage.py makemigrations yourapp --empty并更新生成的文件:

from django.db import migrations

def export_customer_company(apps, schema_editor):
    Customer = apps.get_model('yourapp', 'Customer')
    Company = apps.get_model('yourapp', 'Company')
    for customer in Customer.objects.all():
        customer._company = Company.objects.get_or_create(name=customer.company)[0]
        customer.save()

def revert_export_customer_company(apps, schema_editor):
    Customer = apps.get_model('yourapp', 'Customer')
    Company = apps.get_model('yourapp', 'Company')
    for customer in Customer.objects.filter(_company__isnull=False):
        customer.company = customer._company.name
        customer.save()

class Migration(migrations.Migration):

    dependencies = [
        ('yourapp', 'xxxx_previous_migration'),  # Note this is auto-generated by django
    ]

    operations = [
        migrations.RunPython(export_customer_company, revert_export_customer_company),
    ]

以上迁移将根据填充您的Company模型和Customer._company字段Customer.company

现在,您可以删除旧的Customer.company并重命名Customer._company

class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.ForeignKey(Company)

决赛manage.py makemigrationsmanage.py migrate

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章