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.
| |
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:
| |
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
| |
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:
| |
Then run
| |
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.
