gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:20:34 24 4
gpt4 key购买 nike

场景:
我有一个模型,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创建第一个迁移。然后,您将必须创建一个 data migration。使用 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

关于django - Django迁移时如何设置/提供默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49221515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com