gpt4 book ai didi

python - Django -- 新字段 : How to set default callable for existing objects

转载 作者:太空狗 更新时间:2023-10-30 01:59:08 25 4
gpt4 key购买 nike

我有一个模型:

class Model(models.Model):
price = models.DecimalField(...)

生产数据库中已经有 Model 对象。现在,我将 price_total 字段添加到此模型,该字段不能为 null

class Model(models.Model):
price = models.DecimalField(...)
price_total = models.DecimalField(...)

我希望此 price_total 在迁移后立即等于 price

类似于:

price_total = models.DecimalField(default=this_object.price,...)

是否有可能以某种方式做到这一点?

我唯一知道的是:

  1. 使 price_total 可以为 null
  2. makemigrations + 迁移
  3. 设置 price_total 等于 price 例如通过 django shell
  4. 使 price_total 不可为空
  5. 制作迁移 + 迁移

但是这种方式有很多缺点,你可能会忘记在生产中这样做,它有很多步骤等等......

有没有更好的办法?

最佳答案

您可以通过手动编辑迁移来完成,

  1. 使用 null 进行 makemigrations
  2. 使用 not null 进行 makemigrations
  3. 首先编辑通过从第二个迁移文件添加更新和移动操作的数据迁移来进行迁移
  4. 删除第二个迁移文件,

例如:

from django.db import migrations, models
from django.db.models import F

def set_price_total(apps, schema_editor):
# Change the myapp on your
Model = apps.get_model('myapp', 'Model')
Model.objects.update(price_total=F('price'))


class Migration(migrations.Migration):

dependencies = [
('myapp', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='model',
name='price_total',
field=models.DecimalField(
decimal_places=2, max_digits=10, null=True),
),

migrations.RunPython(set_price_total),

migrations.AlterField(
model_name='model',
name='price_total',
field=models.DecimalField(
decimal_places=2, default=1, max_digits=10),
preserve_default=False,
),
]

关于python - Django -- 新字段 : How to set default callable for existing objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50930821/

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