シードデータ - Django

ディレクトリ構成

  • pythonApp
    • crud
      • crud
        • crud
          • __pycache__
          • __init__.py
          • asgi.py
          • settings.py
          • urls.py
          • wsgi.py
        • fixtures
          • users-data.json
        • member
          • migrations
            • ...
          • templates
            • member
          • __init__.py
          • admin.py
          • apps.py
          • forms.py
          • models.py
          • tests.py
          • urls.py
          • views.py
        • db.sqlite3
        • manage.py
      • include
      • Lib
      • Scripts
      • pyenv.cfg

シードファイルを作成

「 model 」は、「 アプリケーション名.モデル名 」の形で指定します。

pythonApp\crud\crud\fixtures\users-data.json

[
  {
    "model": "member.user",
    "fields": {
      "name": "taro",
      "mail": "taro@example.com",
      "gender": "False",
      "age": "10",
      "birthday": "2019-06-04"
    }
  },
  {
    "model": "member.user",
    "fields": {
      "name": "hanako",
      "mail": "hanako@example.com",
      "gender": "True",
      "age": "20",
      "birthday": "2019-06-04"
    }
  }
]

シードデータを登録するには、loaddata コマンドを使います。

python manage.py loaddata fixtures/users-data.json

複数の json ファイルを登録する場合は、次のようにします。

python manage.py loaddata hoge_data.json foo_data.json

シードデータ作成 - サンプル

import json

data = []
appli_name = "member"
model_name = "user"

model_val = appli_name + "." + model_name
fields = ["name", "mail", "gender", "age", "birthday"]
data_num = 10


for i in range(data_num):
  dic = {}
  dic["model"] = model_val
  dic["fields"] = {}
  
  for j in fields:
    if (j == "name"):
      dic["fields"][j] = j + "-" + str(i + 1)
    elif (j == "mail"):
      dic["fields"][j] = dic["fields"]["name"] + "@example.com"
    elif (j == "gender"):
      dic["fields"][j] = "True"
    elif (j == "age"):
      dic["fields"][j] = i + 1
    elif (j == "birthday"):
      dic["fields"][j] = "1900-01-01"
  
  print(dic)
  data.append(dic)

json_str = json.dumps(data, indent=2)
path = './' + appli_name + '_' + model_name + '.json'

with open(path, 'w') as f:
  f.write(json_str)