모델에 초기 데이터를 제공하는 방법

앱을 처음 설정할 때 하드 코딩된 데이터로 데이터베이스를 미리 채우는 것이 때때로 유용합니다. 마이그레이션 또는 고정 장치와 함께 초기 데이터를 제공할 수 있습니다.

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가 데이터베이스로 가져오는 방법을 알고 있는 데이터의 모음입니다. 데이터가 이미 있는 경우 고정장치를 만드는 가장 간단한 방법은 :tembadmin:’manage.py dumpdata’ 명령을 사용하는 것입니다. 또는 수동으로 고정장치를 작성할 수 있으며 고정장치는 JSON, XML 또는 YAML(PyYAML_installed) 문서로 작성할 수 있습니다. :doc:’직렬화 설명서’는 지원되는 각:ref:’직렬화 형식’에 대한 자세한 정보를 제공합니다.

그러나 한 예로 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로 된 동일한 fixture 가 있습니다.

- model: myapp.person
  pk: 1
  fields:
    first_name: John
    last_name: Lennon
- model: myapp.person
  pk: 2
  fields:
    first_name: Paul
    last_name: McCartney

이 데이터는 앱 안에 있는 “고정장치” 디렉토리에 저장됩니다.

:djadmin:’manage.py loaddata <loaddata>` ``<fixturename>``를 호출하여 데이터를 로드할 수 있습니다. ``<fixturename>``는 당신이 만든 fixture 파일의 이름입니다. :djadmin:`loaddata`를 실행할 때마다 데이터는 고정장치에서 읽혀져 데이터베이스에 다시 로드됩니다. 이는 고정 장치에 의해 생성된 행 중 하나를 변경한 후 :djadmin:`loaddata`를 다시 실행하는 경우, 변경 내용이 모두 지워진다는 의미입니다.

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.

더 보기

또한 :ref:’testing framework’에서는 고정장치를 사용하여 일관된 테스트 환경을 설정할 수 있습니다.

Back to Top