gpt4 book ai didi

python - Django:迁移错误中的加载数据

转载 作者:太空狗 更新时间:2023-10-30 00:27:46 27 4
gpt4 key购买 nike

自从使用 Django 迁移(不是 south)并为其中的固定装置使用加载数据以来,我遇到了一些非常烦人的事情。

这是重现我的问题的简单方法:

  • 创建一个新模型 Testmodel,其中包含 1 个字段 field1(CharField 或其他)
  • 使用 makemigrations 创建关联的迁移(比方说 0001)
  • 运行迁移
  • 并在新表中添加一些数据
  • 将数据转储到夹具 testmodel.json
  • 使用 call_command('loaddata', 'testmodel.json') 创建一个迁移:migration 0002
  • 向模型添加一些新字段:field2
  • 创建关联的迁移(0003)

现在,提交它,并将您的数据库置于更改之前的状态:./manage.py migrate myapp zero。因此,您与尚未收到您的更改的队友处于相同状态。

如果您尝试再次运行 ./manage.py migrate,您将在迁移 0002 处收到一个 ProgrammingError,提示“column field2 不存在”。

这似乎是因为 loaddata 正在查看您的模型(已经有 field2),而不仅仅是将 fixture 应用于数据库。

在团队中工作时,这可能会在多种情况下发生,并且还会导致测试运行器失败。

我是不是搞错了什么?这是一个错误吗?那些情况应该怎么办?

--

我正在使用 Django 1.7

最佳答案

loaddata 命令将简单地调用序列化程序。序列化程序将处理来自 models.py 文件的模型状态,而不是来自当前迁移的模型状态,但是没有什么技巧可以愚弄默认序列化程序。

首先,您不想通过 call_command 而是直接使用该序列化器:

from django.core import serializers

def load_fixture(apps, schema_editor):
fixture_file = '/full/path/to/testmodel.json'
fixture = open(fixture_file)
objects = serializers.deserialize('json', fixture, ignorenonexistent=True)
for obj in objects:
obj.save()
fixture.close()

其次,序列化程序使用的 monkey-patch 应用注册表:

from django.core import serializers

def load_fixture(apps, schema_editor):
original_apps = serializers.python.apps
serializers.python.apps = apps
fixture_file = '/full/path/to/testmodel.json'
fixture = open(fixture_file)
objects = serializers.deserialize('json', fixture, ignorenonexistent=True)
for obj in objects:
obj.save()
fixture.close()
serializers.python.apps = original_apps

现在序列化器将使用来自 apps 的模型状态而不是默认状态,整个迁移过程将会成功。

关于python - Django:迁移错误中的加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32912112/

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