gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:14 25 4
gpt4 key购买 nike

假设我有一个代表我公司产品的模型。每个产品都有一个产品编号(例如 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),
]

关于python - Django 数据库迁移 : merging two fields into one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667638/

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