django-import-export
django-import-export is a versatile Django application and library for importing and exporting data, with seamless integration into the Django admin interface. It supports various data formats like CSV, JSON, and Excel, and allows for robust customization through `Resource` classes for complex data mapping and transformations. The project maintains active development with regular patch releases and significant updates approximately once a year.
Warnings
- breaking Version 4.0.0 introduced significant breaking changes: `base_queryset` was removed (use `get_queryset`), `export_order` default changed, and `fields`, `exclude`, `widgets` behavior was refined. Additionally, Python < 3.9 and Django < 3.2 are no longer supported.
- breaking In v4.0.0, the `import_obj` and `save_row` methods now return a tuple `(obj, new)` to indicate if a new object was created. Also, `get_data_for_export` was renamed to `get_export_data`.
- gotcha When dealing with `ForeignKey` or `ManyToMany` fields, you must explicitly define a `Field` with a `ForeignKeyWidget` or `ManyToManyWidget` and specify the `field` argument (e.g., `'name'`, `'slug'`). Otherwise, the library will attempt to match by primary key (ID) during import, which is often not desired.
- gotcha Importing or exporting very large datasets can lead to memory exhaustion. By default, `queryset` fetching might load all objects into memory.
- deprecated Since v3.0.0, `ImportExportMixin` and `ImportExportModelAdmin` strictly require the `resource_class` attribute to be explicitly set. Inferring the `Resource` from `_meta.model` is no longer supported.
Install
-
pip install django-import-export -
pip install django-import-export[pandas]
Imports
- ModelResource
from import_export.resources import ModelResource
- Field
from import_export.fields import Field
- ForeignKeyWidget
from import_export.widgets import ForeignKeyWidget
- ImportExportModelAdmin
from import_export.admin import ImportExportModelAdmin
Quickstart
import os
import django
from django.conf import settings
from import_export import resources
from import_export.fields import Field
from import_export.widgets import ForeignKeyWidget
# Minimal Django setup for standalone script
if not settings.configured:
settings.configure(
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'import_export',
'my_app', # Placeholder for your app
],
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
DEBUG=True,
USE_TZ=True,
TIME_ZONE='UTC',
SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'super-secret-key-for-testing'),
TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
}],
ROOT_URLCONF='django_import_export.urls', # Dummy URLconf required by django.setup()
)
django.setup()
from django.db import models
# 1. Define your Django Models (example)
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self): return self.name
class Meta: app_label = 'my_app'
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
def __str__(self): return self.name
class Meta: app_label = 'my_app'
# Need to create tables for these models in the in-memory DB for the example
from django.db import connection
with connection.schema_editor() as schema_editor:
schema_editor.create_model(Category)
schema_editor.create_model(Product)
# 2. Define a Resource for your Model
class ProductResource(resources.ModelResource):
category = Field(
column_name='category_name',
attribute='category',
widget=ForeignKeyWidget(Category, 'name') # Match category by name during import/export
)
class Meta:
model = Product
fields = ('id', 'name', 'price', 'category',) # Fields to include
export_order = ('id', 'name', 'price', 'category',) # Order for export
# 3. Use the Resource to export data programmatically
category_electronics = Category.objects.create(name='Electronics')
Product.objects.create(name='Laptop', price=1200.00, category=category_electronics)
Product.objects.create(name='Mouse', price=25.00, category=category_electronics)
product_resource = ProductResource()
dataset = product_resource.export()
print("\n--- Exported CSV data ---")
print(dataset.csv)