---
title: "如何为模型提供初始数据"
version: 4.1
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/4.1/howto/initial-data/
canonical: https://djangodocs.dev/zh-hans/4.1/howto/initial-data/
---
# 如何为模型提供初始数据

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.

## 通过迁移提供初始数据

若你想为应用自动载入初始数据，创建一个 [数据迁移](/zh-hans/4.1/topics/migrations/#data-migrations)。创建测试数据库时会运行迁移，所以可以用这里的数据， [一些限制](/zh-hans/4.1/topics/testing/overview/#test-case-serialized-rollback) 主题。

## 通过固定内容提供数据

你也能通过固定内容提供数据，不过，这些数据不会自动加载，除非你使用 [`TransactionTestCase.fixtures`](/zh-hans/4.1/topics/testing/tools/#django.test.TransactionTestCase.fixtures)。

固定内容是一个 Django 知道如何导入数据库的集合。若你已有一些可用数据，最直接的创建固定内容的方式是使用  [`manage.py dumpdata`](/zh-hans/4.1/ref/django-admin/#django-admin-dumpdata) 命令。或者，你可以手写固定内容；固定数据能被写作 JSON，XML 或 YAML （要求已安装 [PyYAML](https://pyyaml.org/)）文档。 [序列化文档](/zh-hans/4.1/topics/serialization/) 拥有更多这些支持的 [序列化格式](/zh-hans/4.1/topics/serialization/#serialization-formats) 的细节信息。

举个例子，这有一个固定内容，描述了一个 `Person` 模型写成 JSON 后的样子：

```js
[
  {
    "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 格式：

```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`](/zh-hans/4.1/ref/django-admin/#django-admin-loaddata)
`<fixturename>`, where `<fixturename>` is the name of the fixture file
you've created. Each time you run [`loaddata`](/zh-hans/4.1/ref/django-admin/#django-admin-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`](/zh-hans/4.1/ref/django-admin/#django-admin-loaddata)
again, you'll wipe out any changes you've made.

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

默认情况下，Django 在每个应用的 `fixtures` 目录中查找固定内容。你可以将配置项 [`FIXTURE_DIRS`](/zh-hans/4.1/ref/settings/#std-setting-FIXTURE_DIRS) 设为一个 Django 需要额外寻找的目录列表。

[`manage.py loaddata`](/zh-hans/4.1/ref/django-admin/#django-admin-loaddata) 时，你也能指定一个到固定内容文件的路径，这将会覆盖查找常规目录的行为。

> **See also**
>
> 固定内容通常备 [测试框架](/zh-hans/4.1/topics/testing/tools/#topics-testing-fixtures) 用于创建永久的测试环境。
