场景:
我有一个模特,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 makemigrations
和manage.py migrate
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句