【问题标题】:Django Custom Migration Not ExecutingDjango 自定义迁移未执行
【发布时间】:2018-11-03 23:01:49
【问题描述】:

所以我在 django 数据库表中添加了一个新的“状态”字段。该字段需要一个默认值,因此我将其默认为“New”,但随后我添加了一个自定义迁移文件,该文件对该表中的所有对象调用 save() 方法,因为我已覆盖 save() 以进行检查另一个表并从中提取正确的状态。但是,运行此迁移后,所有状态仍设置为“新建”,因此看起来保存未执行。我通过在运行迁移后手动调用所有对象的保存来测试这一点,并且状态按预期更新。

这是 models.py 中的表格模型:

class SOS(models.Model):
    number = models.CharField(max_length=20, unique=True)
    ...
    # the default="New" portion is missing here because I have a migration to remove it after the custom migration (shown below) that saves the models
    status = models.CharField(max_length=20)

    def save(self, *args, **kwargs):
        self.status = self.history_set.get(version=self.latest_version).status if self.history_set.count() != 0 else "New"
        super(SOS, self).save(*args, **kwargs)

这里是迁移:

# Generated by Django 2.0.5 on 2018-05-23 13:50
from django.db import migrations, models

def set_status(apps, schema_editor):
    SOS = apps.get_model('sos', 'SOS')
    for sos in SOS.objects.all():
        sos.save()

class Migration(migrations.Migration):

    dependencies = [
        ('sos', '0033_auto_20180523_0950'),
    ]

    operations = [
        migrations.RunPython(set_status),
    ]

所以对我来说似乎很清楚我在迁移时做错了什么,但我将它与我在Django Documentation 中看到的完全匹配,我还将它与this StackOverflow 答案进行了比较,我可以'没有看到我做错了什么。运行迁移时没有错误,但我编写的自定义迁移几乎立即运行,这看起来很奇怪,因为当我手动保存时,保存所有 300 多个条目大约需要 5 秒。

有什么建议吗?

附:如果有任何我忽略的相关细节,请告诉我。

【问题讨论】:

    标签: python mysql django django-migrations


    【解决方案1】:

    当您运行迁移并从应用程序获取模型时,您不能使用自定义管理器或自定义保存或创建或类似的东西。这个模型只有字段,仅此而已。如果你想实现你想要的,你应该像这样将你的逻辑添加到你的迁移中:

    # comment to be more than 6 chars...
    def set_status(apps, schema_editor):
        SOS = apps.get_model('sos', 'SOS')
        for sos in SOS.objects.all():
            if sos.history_set.exists():
                sos.status = sos.history_set.get(version=sos.latest_version).status 
            else:
                sos.status =  "New"
            sos.save()
    

    【讨论】:

    • 只需要删除对自我的引用,但其他方面完美!现在我觉得很傻,不考虑尝试……谢谢!
    • 另外最好使用 exists() insted of count() == 0
    • 明白了。我会更新我的存档以使用它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-12-16
    • 2020-10-08
    • 2013-01-16
    • 2012-07-15
    • 2014-11-19
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多