Open2
Djangoいろいろ

DjangoでCSV出力 基本構文
def csv_export(request):
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = 'attachment; filename="filename.csv"'
writer = csv.writer(response)
writer.writerow(["1", "test1"])
writer.writerow(["2", "test2"])
writer.writerow(["3", "test3"])
return response

fixture による Django のテストデータ作成
fixture とは
- Django に fixtures ディレクトリを設けると、そこに初期データを投入できる
- fixtures ディレクトリは各アプリケーションディレクトリの中に作成する
- データの形式は json、xml、yarl の 3 種類である
手順
-
マイグレーションなどは済ませておく
-
todo
ディレクトリ(アプリケーションディレクトリ)にfixtures
ディレクトリを作成する -
fixtures
ディレクトリ内にtest_data.json
ファイルを作成し、以下を入力する書き方[ { "model": "アプリケーション名.モデル名", "pk": 数字, "fields": { "フィールド名": "データ" } } ]
test_data.json[ { "model": "todo.ToDo", "pk": 1, "fields": { "todo": "洗濯" } }, { "model": "todo.ToDo", "pk": 2, "fields": { "todo": "掃除" } }, { "model": "todo.ToDo", "pk": 3, "fields": { "todo": "基本情報技術者試験の勉強" } } ]
-
以下のコマンドを実行し、データベースに反映させる。成功すると 2 行目のメッセージが出る
(env)$ python manage.py loaddata fixture1.json Installed 3 object(s) from 1 fixture(s)