22
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Djangoの初期データ投入機能についてメモ

Posted at

fixture というものがある

詳しくはここDjangoのドキュメント

JSON, XML, YAMLで書ける

使い方

1. このような構造にする

.
└── mysite
    ├── db.sqlite3
    ├── manage.py
    ├── mysite
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    └── polls
        ├── __init__.py
        ├── admin.py
        ├── apps.py
        ├── migrations
        ├── models.py
        ├── templates
        ├── tests.py
        ├── urls.py
        ├── views.py
        └── fixtures # 追加

2. fixturesディレクトリに投入したいデータを書いたJSONファイル追加

fixtures
├── data1.json
├── data2.json
├── data3.json
└── data4.json

3. loaddata を使って読み込む

$ python manage.py loaddata polls/fixtures/data1.json

4. 反対にDBのデータを出力したいときは dumpdata を使う

$ python manage.py dumpdata --indent=2 --format=json polls.modelname > polls/fixtures/data.json

日本語が含まれている場合、エスケープされてしまうので、エスケープされたままだと困る場合は変換する必要がある。

22
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?