让我们从您的原始模型开始,一步一步地进行。
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
。然后你必须创建一个数据迁移 https://docs.djangoproject.com/en/stable/howto/writing-migrations/。使用创建迁移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)
Final manage.py makemigrations
and manage.py migrate
.