I recently switched from Django 1.6 to 1.7, and I began using migrations (I never used South).

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

现在,我开始使用迁移,此行为已弃用:

If an application uses migrations, there is no automatic loading of fixtures. Since migrations will be required for applications in Django 2.0, this behavior is considered deprecated. If you want to load initial data for an app, consider doing it in a data migration. (https://docs.djangoproject.com/en/1.7/howto/initial-data/#automatically-loading-initial-data-fixtures)

The official documentation does not have a clear example on how to do it, so my question is :

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

  1. Write Python code with multiple calls to mymodel.create(...),
  2. Use or write a Django function (like calling loaddata) to load data from a JSON fixture file.

我更喜欢第二种 Select .

I don't want to use South, as Django seems to be able to do it natively now.

推荐答案

Update:有关此解决方案可能导致的问题,请参阅下面@GwynBleidD的 comments ,并参阅下面@Rockallite的答案,以了解对future 模型更改更持久的方法.


假设你有一个<yourapp>/fixtures/initial_data.json英寸的fixture 文件

  1. Create your empty migration:

    In Django 1.7:

    python manage.py makemigrations --empty <yourapp>
    

    In Django 1.8+, you can provide a name:

    python manage.py makemigrations --empty <yourapp> --name load_intial_data
    
  2. Edit your migration file <yourapp>/migrations/0002_auto_xxx.py

    2.1. Custom implementation, inspired by Django' loaddata (initial answer):

    import os
    from sys import path
    from django.core import serializers
    
    fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures'))
    fixture_filename = 'initial_data.json'
    
    def load_fixture(apps, schema_editor):
        fixture_file = os.path.join(fixture_dir, fixture_filename)
    
        fixture = open(fixture_file, 'rb')
        objects = serializers.deserialize('json', fixture, ignorenonexistent=True)
        for obj in objects:
            obj.save()
        fixture.close()
    
    def unload_fixture(apps, schema_editor):
        "Brutally deleting all entries for this model..."
    
        MyModel = apps.get_model("yourapp", "ModelName")
        MyModel.objects.all().delete()
    
    class Migration(migrations.Migration):  
    
        dependencies = [
            ('yourapp', '0001_initial'),
        ]
    
        operations = [
            migrations.RunPython(load_fixture, reverse_code=unload_fixture),
        ]
    

    2.2. load_fixture美元的简单解决方案(根据@juliocesar的建议):

    from django.core.management import call_command
    
    fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures'))
    fixture_filename = 'initial_data.json'
    
    def load_fixture(apps, schema_editor):
        fixture_file = os.path.join(fixture_dir, fixture_filename)
        call_command('loaddata', fixture_file) 
    

    Useful if you want to use a custom directory.

    2.3. Simplest:app_label呼叫loaddata将自动从<yourapp>fixtures dir加载装置:

    from django.core.management import call_command
    
    fixture = 'initial_data'
    
    def load_fixture(apps, schema_editor):
        call_command('loaddata', fixture, app_label='yourapp') 
    

    If you don't specify app_label, loaddata will try to load fixture filename from all apps fixtures directories (which you probably don't want).

  3. 运行它

Json相关问答推荐

按照对象键的值对PostgreSQL JSONB对象进行排序'

您可以使用Jolt对JSON执行OR条件吗

由于无效的UTF-8开始字节0xa0,JSON被拒绝,但编码似乎有效

在Ansible中从json中提取特定数据

bash用jq获取第二条JSON记录

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

Rust实现:高效解析任意大小的JSON数组

如何加入或合并列表元素列表(未知长度)

JOLT - 如果对象内部存在键,则将对象移动到数组

Rails 控制器无需编码即可渲染 json

如何在 onClick 事件处理程序中识别在同一 map 上绘制的多个多边形中的哪个(使用 react-leaflet)被单击?

应该使用什么标头将 GZIP 压缩 JSON 从 Android 客户端发送到服务器?

使用绝对或相对路径在 curl 请求中发送 json 文件

如何在 json 编码字符串内的子数组数据周围添加方括号?

PostgreSQL 中的 JSON 模式验证?

使用 JSON.Net 的 C# 到 JSON 序列化

将 json 转换为 C# 数组?

严重:找不到媒体类型 = 应用程序/json、类型 = 类 com.jersey.jaxb.Todo、通用类型 = 类 com.jersey.jaxb.Todo 的 MessageBodyWriter

在没有 ASP.NET Core 的情况下将 IConfigurationSection 绑定到复杂对象

从 Ruby 中的 JSON 文件解析并从嵌套哈希中提取数字