首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Django 1.7+加载初始数据和数据迁移

问用Django 1.7+加载初始数据和数据迁移
EN

Stack Overflow用户
提问于 2014-09-21 15:37:13
回答 8查看 42.7K关注 0票数 102

我最近从Django 1.6切换到1.7,我开始使用迁移(我从未使用过South)。

在1.7之前,我使用fixture/initial_data.json文件加载初始数据,该文件使用python manage.py syncdb命令加载(在创建数据库时)。

现在,我开始使用迁移,不推荐这种行为:

如果应用程序使用迁移,则不会自动加载固定装置。因为Django 2.0中的应用程序需要迁移,因此这种行为被认为是不可取的。如果您想要为应用程序加载初始数据,请考虑在数据迁移中这样做。(https://docs.djangoproject.com/en/1.7/howto/initial-data/#automatically-loading-initial-data-fixtures)

正式文件没有明确的例子来说明如何做到这一点,所以我的问题是:

使用数据迁移导入此类初始数据的最佳方法是什么:

  1. 用多个调用mymodel.create(...)编写Python代码,
  2. 使用或编写Django函数(loaddata)从JSON夹具文件中加载数据。

我更喜欢第二种选择。

我不想使用South,因为Django现在似乎能够在本地使用它了。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2014-09-22 19:38:14

更新:请参阅@GwynBleidD下面的评论,以了解该解决方案可能引发的问题,并在下面查看@Rockallite的答案,以获得更适合未来模型更改的方法。

假设您在<yourapp>/fixtures/initial_data.json中有一个夹具文件

  1. 创建空迁移: 在Django 1.7: python manage.py生成--空的 在Django 1.8+中,您可以提供一个名称: python manage.py生成--空的--名称load_intial_data
  2. 编辑您的迁移文件<yourapp>/migrations/0002_auto_xxx.py 2.1。自定义实现,受Django‘loaddata的启发(初始答案): 从sys导入路径导入os (从os.path.abspath(os.path.join(os.path.dirname(__file__),‘../ django.core’)导入) fixture_filename = 'initial_data.json‘def load_fixture(apps,schema_editor):fixture_file = os.path.join( fixture_dir,fixture_filename) initial_data.json= open(fixture_file,'rb')对象= serializers.deserialize('json',夹具,ignorenonexistent=True)对于对象中的obj : obj.save() fixture.close() def unload_fixture(app,schema_editor):“残忍地删除该模型的所有条目.”MyModel = apps.get_model("yourapp","ModelName") MyModel.objects.all().delete()类迁移(migrations.Migration):依赖关系= ('yourapp','0001_initial'),操作= migrations.RunPython(load_fixture,reverse_code=unload_fixture), 2.2。load_fixture的一个更简单的解决方案(per @juliocesar的建议): ) os.path.abspath(os.path.join(os.path.dirname(__file__),= 'initial_data.json‘def load_fixture(app,schema_editor):fixture_file = os.path.join( fixture_dir,fixture_filename) call_command (“loaddata”,fixture_file) 如果要使用自定义目录,则非常有用。 2.3。最简单的:用app_label调用loaddata将自动从<yourapp>的fixtures dir加载夹具:从django.core.management导入django.core.management call_command <yourapp>= 'initial_data‘def load_fixture(应用程序,schema_editor):call_command('loaddata',loaddata,app_label='yourapp') 如果不指定app_label__,加载数据将尝试从all应用程序固定目录(您可能不想要的目录)加载fixture文件名。
  3. 运行它 python manage.py迁移
票数 86
EN

Stack Overflow用户

发布于 2016-09-28 09:38:05

短版

您应该在数据迁移中直接使用而不是使用loaddata管理命令。

代码语言:javascript
复制
# Bad example for a data migration
from django.db import migrations
from django.core.management import call_command


def load_fixture(apps, schema_editor):
    # No, it's wrong. DON'T DO THIS!
    call_command('loaddata', 'your_data.json', app_label='yourapp')


class Migration(migrations.Migration):
    dependencies = [
        # Dependencies to other migrations
    ]

    operations = [
        migrations.RunPython(load_fixture),
    ]

长版

loaddata利用django.core.serializers.python.Deserializer,它使用最先进的模型来反序列化迁移中的历史数据。这是不正确的行为。

例如,假设有一个数据迁移使用loaddata管理命令从一个夹具加载数据,并且它已经应用于您的开发环境。

稍后,您决定向相应的模型中添加一个新的必需字段,因此您可以这样做,并对更新的模型进行新的迁移(并且可能在./manage.py makemigrations提示您时向新字段提供一个一次性值)。

运行下一次迁移,一切都很好。

最后,完成了Django应用程序的开发,并将其部署到生产服务器上。现在,是时候从零开始在生产环境上运行整个迁移了。

然而,数据迁移失败了。这是因为表示当前代码的loaddata命令中的反序列化模型无法保存为您添加的新的必需字段的空数据。原来的夹具缺乏必要的数据!

但是,即使您用新字段所需的数据更新夹具,--数据迁移仍然失败--。当数据迁移运行时,将相应的列添加到数据库中的下一次迁移尚未应用。无法将数据保存到不存在的列中!

结论:在数据迁移中,loaddata命令引入了模型与数据库之间潜在的不一致性。您肯定应该在数据迁移中直接使用,而不是。

解决方案

loaddata命令依赖于django.core.serializers.python._get_model函数从一个夹具中获取相应的模型,这将返回模型的最新版本。我们需要对它进行猴子修补,这样它才能得到历史模型。

(以下代码适用于Django 1.8.x)

代码语言:javascript
复制
# Good example for a data migration
from django.db import migrations
from django.core.serializers import base, python
from django.core.management import call_command


def load_fixture(apps, schema_editor):
    # Save the old _get_model() function
    old_get_model = python._get_model

    # Define new _get_model() function here, which utilizes the apps argument to
    # get the historical version of a model. This piece of code is directly stolen
    # from django.core.serializers.python._get_model, unchanged. However, here it
    # has a different context, specifically, the apps variable.
    def _get_model(model_identifier):
        try:
            return apps.get_model(model_identifier)
        except (LookupError, TypeError):
            raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)

    # Replace the _get_model() function on the module, so loaddata can utilize it.
    python._get_model = _get_model

    try:
        # Call loaddata command
        call_command('loaddata', 'your_data.json', app_label='yourapp')
    finally:
        # Restore old _get_model() function
        python._get_model = old_get_model


class Migration(migrations.Migration):
    dependencies = [
        # Dependencies to other migrations
    ]

    operations = [
        migrations.RunPython(load_fixture),
    ]
票数 61
EN

Stack Overflow用户

发布于 2015-01-06 21:27:00

在一些评论(即n_o)的启发下,以及我将大量initial_data.*文件分散在多个应用程序的事实下,我决定创建一个Django应用程序,以方便这些数据迁移的创建。

使用django-迁移-固定装置,您可以简单地运行以下管理命令,它将搜索所有INSTALLED_APPS中的initial_data.*文件,并将它们转换为数据迁移。

代码语言:javascript
复制
./manage.py create_initial_data_fixtures
Migrations for 'eggs':
  0002_auto_20150107_0817.py:
Migrations for 'sausage':
  Ignoring 'initial_data.yaml' - migration already exists.
Migrations for 'foo':
  Ignoring 'initial_data.yaml' - not migrated.

有关安装/使用说明,请参见django-迁移-固定装置。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25960850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档