【问题标题】:Django database migration: merging two fields into oneDjango 数据库迁移:将两个字段合并为一个
【发布时间】:2016-04-12 13:56:02
【问题描述】:

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

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 中编写数据库迁移来实现这一点?

【问题讨论】:

  • 我已经阅读了有关“编写数据库迁移”和“迁移”的 Django 文档,不幸的是,文档和 Google 都没有很多示例。我不知道我的操作[] 列表在我的迁移文件中对于这个特定的应用程序应该是什么样子。

标签: python django database-migration django-migrations django-database


【解决方案1】:

我没有测试它,但这样的东西应该可以工作。首先创建一个迁移添加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),
    ]

【讨论】:

  • 我会试试这个。难道你也不必删除旧字段吗?
  • 是的,但是您必须稍后在另一个迁移中删除它们。这样做要小心。
  • 是否可以在同一迁移中创建和修改字段?
猜你喜欢
  • 1970-01-01
  • 2014-09-17
  • 2013-12-08
  • 2021-09-20
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多