Python Django数据库迁移:将两个字段合并为一个
假设我有一个代表我公司产品的模型。每个产品都有一个产品编号(例如5928523),以及一个表示是否为实验产品的布尔值Python Django数据库迁移:将两个字段合并为一个,python,django,database-migration,django-migrations,django-database,Python,Django,Database Migration,Django Migrations,Django Database,假设我有一个代表我公司产品的模型。每个产品都有一个产品编号(例如5928523),以及一个表示是否为实验产品的布尔值 class Product(models.Model): product_number = models.IntegerField() experimental = models.BooleanField(default=False) 假设我想将这两个字段合并为一个字符字段,即产品ID。因此,产品编号为3892的实验性产品将变成“X3892”,而产品编号为93
class Product(models.Model):
product_number = models.IntegerField()
experimental = models.BooleanField(default=False)
假设我想将这两个字段合并为一个字符字段,即产品ID。因此,产品编号为3892的实验性产品将变成“X3892”,而产品编号为937的非实验性产品将变成“937”
如何在Django中编写数据库迁移来实现这一点?我没有测试它,但类似的东西应该可以工作。首先创建迁移以添加
产品\u id
然后创建一个空迁移,并根据需要调整create_product_id
请记住将您的AppName更改为应用程序的名称
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def create_product_id(apps, schema_editor):
Product = apps.get_model("yourappname", "Product")
for product in Product.objects.all():
p_id = str(product.product_number)
if product.experimental:
p_id = "X" + p_id
product.product_id = p_id
product.save()
class Migration(migrations.Migration):
initial = True
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
migrations.RunPython(create_product_id),
]
使用数据迁移我已经阅读了关于“编写数据库迁移”和“迁移”的Django文档,不幸的是,文档和Google都没有很多例子。我不知道我的operations[]列表在这个特定应用程序的迁移文件中应该是什么样子。我将尝试一下。您不也必须删除旧字段吗?是的,但您必须在以后的另一次迁移中删除它们。请小心。是否可以在同一迁移中创建字段并修改它们?
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def create_product_id(apps, schema_editor):
Product = apps.get_model("yourappname", "Product")
for product in Product.objects.all():
p_id = str(product.product_number)
if product.experimental:
p_id = "X" + p_id
product.product_id = p_id
product.save()
class Migration(migrations.Migration):
initial = True
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
migrations.RunPython(create_product_id),
]