LoginSignup
0
3

More than 3 years have passed since last update.

Django でexcel,csvインポート、エクスポート

Last updated at Posted at 2020-01-04

Djangのmodelをexcel,csvからインポートしたり、エクスポートしたりする方法

django-import-exportプラグインを使う

手っ取り早くインポートエクスポートが使えるようになります。
django-import-export

インストール方法
https://kurozumi.github.io/django-import-export/installation.html

各アプリフォルダ内のadmin.pyにてModelAdminの代わりにImportExportActionModelAdminを使う

from import_export.admin import ImportExportActionModelAdmin
from sampleapp.models import SampleData

class SampleDataAdmin(ImportExportActionModelAdmin):
    names = [f.name for f in SampleData._meta.get_fields() if not isinstance(f, models.ManyToOneRel)]
    list_display = names
    list_filter = ['sample_row1', 'sample_row2', 'sample_row3',]

これだけで、csv,excelの他、jsonやyamlが使用できるようになります。
インポートはadminの一覧画面の右上、エクスポートは操作(action)よりデータを選択して実行します。

スクラッチで実装

django-import-exportプラグインを使うと楽なのですが、どうしても使いたくない場合の実装方法は、下記リンク先に記載されています。このサイトはDjango adminの勉強にも良いと思います。
https://books.agiliq.com/projects/django-admin-cookbook/en/latest/export.html
https://books.agiliq.com/projects/django-admin-cookbook/en/latest/import.html

0
3
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
0
3