This page looks best with JavaScript enabled

Django Initial Data with Fixtures

 ·  β˜• 3 min read

1. Characteristics of Fixtures

Fixtures are a new way to provide initial data, and they are used by Django’s test framework to handle test data for unit tests. Unlike SQL files, a fixture can provide a serialized file that Django’s serialization system understands; it is read, automatically converted into the corresponding model, and then saved into the database.

2. Exporting Data

Export the data of app_name as initial_data.json.

1
python manage.py    dumpdata app_name > initial_data.json

3. Importing Data

There are two ways to import: one is to run the loaddata command, and the other is to insert data through a migrations file when the database changes.

3.1 Importing Data with loaddata

Store the data in the app’s fixtures directory, then run the import command:

1
2
python manage.py    loaddata  app_name/fixtures/initial_data.json
> Installed 1 object(s) from 1 fixture(s)

Because the model is already specified in initial_data.json, no extra arguments are needed here to import the data as expected. Note that the file exported by dumpdata contains a pk; if that pk already exists in the database, the data will not be imported again.

3.2 Importing Data with a Python Migration

In Django’s settings.py file, add

1
2
3
4
import os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR, PROJECT_MODULE_NAME = os.path.split(PROJECT_ROOT)
FIXTURE_FILE = os.path.join(PROJECT_DIR, PROJECT_MODULE_NAME, 'app_name/fixtures/initial_data.json')

to specify the directory of the initial data file.

Use the python manage.py makemigrations --empty app_name command to create an empty Python file under app_name’s migrations directory. Its contents are as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
from django.db import migrations
from settings import FIXTURE_FILE
from app_name.models import AppModel


def forwards_func(apps, schema_editor):
    try:
        json_data = open(FIXTURE_FILE)
        _obj = json.load(json_data)
        _obj = [i['fields'] for i in user_obj]
        _list = [AppModel(username=i['username'], last_name=i['last_name'], password=i['password']
                              ) for i in _obj]
        if _list:
            AppModel.objects.bulk_create(_list)
        json_data.close()
    except:
        pass


class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(forwards_func),
    ]

Then run

1
python manage.py migrate app_name

Django Migration provides two functions for operating on data

  • forwards_func is used to perform the insert operation.
  • reverse_func is used to perform the rollback operation.

Note that here the initial data is obtained by opening a json file; you can also obtain initial data by hard-coding it into a Python file, reading Excel, reading TXT, and so on.

4. When to Use It

Fixtures are suited to a small amount of initial data, because they use Django’s serialization feature and therefore do not depend on a specific database. They are not as fast to execute as SQL, because objects have to be created. In addition, this feature can be used when you switch database platforms β€” for example, if I want to move a system from Mysql to PostgreSQL, I can use fixtures to export and import the data.


WeChat Official Account
WRITTEN BY
WeChat Official Account