Skip to main content
 首页 » 编程设计

python之Django 数据库迁移 : merging two fields into one

2024年10月24日32exmyth

假设我有一个代表我公司产品的模型。每个产品都有一个产品编号(例如 5928523),以及一个表示它是否为实验产品的 bool 值。

class Product(models.Model): 
 
    product_number = models.IntegerField() 
    experimental = models.BooleanField(default=False) 

假设我想将这两个字段合并为一个字符字段,即产品 ID。因此,产品编号为 3892 的实验产品将变为“X3892”,而产品编号为 937 的非实验产品将变为“937”。

class Product(models.Model): 
 
    product_id = models.CharField() 

我将如何在 Django 中编写数据库迁移来实现这一点?

请您参考如下方法:

我没有测试它,但像这样的东西应该可以工作。首先创建一个迁移以添加 product_id。

然后创建一个空迁移并根据需要调整 create_product_id。

请记住将 yourappname 更改为您的应用名称。

# -*- 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), 
    ]