为模型提供初始化的数据

It's sometimes useful to pre-populate your database with hard-coded data whenyou're first setting up an app. You can provide initial data with migrations orfixtures.

Providing initial data with migrations

If you want to automatically load initial data for an app, create adata migration. Migrations are run when setting up thetest database, so the data will be available there, subject to somelimitations.

Providing data with fixtures

You can also provide data using fixtures, however, this data isn't loadedautomatically, except if you use TransactionTestCase.fixtures.

A fixture is a collection of data that Django knows how to import into adatabase. The most straightforward way of creating a fixture if you've alreadygot 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 supportedserialization formats.

As an example, though, here's what a fixture for a simple Person model mightlook like in JSON:

  1. [
  2. {
  3. "model": "myapp.person",
  4. "pk": 1,
  5. "fields": {
  6. "first_name": "John",
  7. "last_name": "Lennon"
  8. }
  9. },
  10. {
  11. "model": "myapp.person",
  12. "pk": 2,
  13. "fields": {
  14. "first_name": "Paul",
  15. "last_name": "McCartney"
  16. }
  17. }
  18. ]

And here's that same fixture as YAML:

  1. - model: myapp.person
  2. pk: 1
  3. fields:
  4. first_name: John
  5. last_name: Lennon
  6. - model: myapp.person
  7. pk: 2
  8. fields:
  9. first_name: Paul
  10. 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 fileyou've created. Each time you run loaddata, the data will be readfrom the fixture and re-loaded into the database. Note this means that if youchange one of the rows created by a fixture and then run loaddataagain, 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 forfixtures. You can set the FIXTURE_DIRS setting to a list ofadditional directories where Django should look.

When running manage.py loaddata, you can alsospecify a path to a fixture file, which overrides searching the usualdirectories.

参见

Fixtures are also used by the testing framework to help set up a consistent test environment.