如何为模型提供初始数据

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.

通过迁移提供初始数据

若你想为应用自动载入初始数据,创建一个 数据迁移。创建测试数据库时会运行迁移,所以可以用这里的数据, 一些限制 主题。

通过固定内容提供数据

你也能通过固定内容提供数据,不过,这些数据不会自动加载,除非你使用 TransactionTestCase.fixtures

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

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

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

你会将该数据存入应用中的 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.

Django 从哪里寻找固定内容文件

默认情况下,Django 在每个应用的 fixtures 目录中查找固定内容。你可以将配置项 FIXTURE_DIRS 设为一个 Django 需要额外寻找的目录列表。

manage.py loaddata 时,你也能指定一个到固定内容文件的路径,这将会覆盖查找常规目录的行为。

参见

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