如何为模型提供初始数据

It's sometimes useful to prepopulate your database with hard-coded data when you're first setting up an app. You can provide initial data with migrations or fixtures.

Provide initial data with migrations

To automatically load initial data for an app, create a data migration. Migrations are run when setting up the test database, so the data will be available there, subject to some limitations.

Provide data with fixtures

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

固定内容是一个 Django 知道如何导入数据库的集合。若你已有一些可用数据,最直接的创建固定内容的方式是使用 manage.py dumpdata 命令。或者,你可以手写固定内容;固定数据能被写作 JSON,XML 或 YAML (要求已安装 PyYAML)文档。 序列化文档 拥有更多这些支持的 序列化格式 的细节信息。

举个例子,这有一个固定内容,描述了一个 Person 模型写成 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"
    }
  }
]

以下是一样的固定内容,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

你会将该数据存入应用中的 fixtures 字典。

You can load data by calling 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 reloaded 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.

Tell Django where to look for fixture files

By default, Django looks for fixtures in the fixtures directory inside each app for, so the command loaddata sample will find the file my_app/fixtures/sample.json. This works with relative paths as well, so loaddata my_app/sample will find the file my_app/fixtures/my_app/sample.json.

Django also looks for fixtures in the list of directories provided in the FIXTURE_DIRS setting.

To completely prevent default search form happening, use an absolute path to specify the location of your fixture file, e.g. loaddata /path/to/sample.

Namespace your fixture files

Django will use the first fixture file it finds whose name matches, so if you have fixture files with the same name in different applications, you will be unable to distinguish between them in your loaddata commands. The easiest way to avoid this problem is by namespacing your fixture files. That is, by putting them inside a directory named for their application, as in the relative path example above.

参见

固定内容通常备 测试框架 用于创建永久的测试环境。