As the name suggests, this is a library to handle importing and exporting data. The django-import-export library
supports multiple formats, including xls, csv, json, yaml, and all other formats supported by
tablib. It also have a Django admin integration, which is really convenient to use.
Installation
Pip is the way to go:
Update your settings.py:
There is also an optional configuration that I usually add:
The default value is False. It determines if the library will use database transactions on data import, just to be
on the safe side.
Resources
The django-import-export library work with the concept of Resource, which is class definition very similar to
how Django handle model forms and admin classes.
In the documentation the authors suggest to put the code related to the resources inside the admin.py file. But
if the implementation is not related to the Django admin, I usually prefer to create a new module named
resources.py inside the app folder.
models.py
resources.py
This is the simplest definition. You can pass several configurations to the Meta class like fields, exclude, etc.
See the documentation for more details.
Exporting Data
Exporting data as CSV
Exporting data as JSON
Exporting data as YAML
Filtering the data
Views Example
Exporting to CSV view:
Exporting to JSON view:
Exporting to Excel view:
Importing Data
Consider the file new_persons.csv:
The id must be present because it is the primary key. But it will be generated though, so we don’t need to specify
the value.
import.html
views.py
Django Admin
Simply use ImportExportModelAdmin instead of ModelAdmin.
admin.py
And you will already notice the Import and Export buttons.
The import functionaly come with a nice diff, when importing existing items:
This is a great Django library. There is much more you can do with it. Totally worth having a look on the
API reference.