Providing initial data for modelsÂś
Itâs sometimes useful to pre-populate your database with hard-coded data when youâre first setting up an app. You can provide initial data with fixtures or migrations.
Providing initial data with fixturesÂś
A fixture is a collection of data that Django knows how to import into a
database. The most straightforward way of creating a fixture if youâve already
got some data is to use the manage.py dumpdata command.
Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML
(with PyYAML installed) documents. The serialization documentation has more details about each of these supported
serialization formats.
As an example, though, hereâs what a fixture for a simple Person model might
look like in JSON:
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Paul",
"last_name": "McCartney"
}
}
]
And hereâs that same fixture as YAML:
- model: myapp.person
pk: 1
fields:
first_name: John
last_name: Lennon
- model: myapp.person
pk: 2
fields:
first_name: Paul
last_name: McCartney
Youâll store this data in a fixtures directory inside your app.
Loading data is easy: just call manage.py loaddata
<fixturename>, where <fixturename> is the name of the fixture file
youâve created. Each time you run loaddata, the data will be read
from the fixture and re-loaded into the database. Note this means that if you
change one of the rows created by a fixture and then run loaddata
again, youâll wipe out any changes youâve made.
Where Django finds fixture filesÂś
By default, Django looks in the fixtures directory inside each app for
fixtures. You can set the FIXTURE_DIRS setting to a list of
additional directories where Django should look.
When running manage.py loaddata, you can also
specify a path to a fixture file, which overrides searching the usual
directories.
See also
Fixtures are also used by the testing framework to help set up a consistent test environment.