Import Export
Key Features
- Supports Multiple Formats:
- File formats: CSV, Excel (XLSX), JSON, YAML, etc.
- Custom formats can also be implemented.
- Seamless Integration with Django Admin:
- Import and export directly from the Django admin interface.
- Buttons are added to the change list page for importing and exporting data.
- Customizable Import/Export Logic:
- Allows you to customize how data is imported/exported by overriding specific methods.
- Supports pre-processing and post-processing of data.
- Error Handling:
- Detailed error reports are provided for failed imports, allowing you to identify problematic rows.
- Queryset Exports:
- Export only specific rows or data subsets using querysets.
Installation
Install the package:
pip install django-import-export
Add it to your
INSTALLED_APPS
insettings.py
:= [ INSTALLED_APPS ...,'import_export', ]
Add the
ImportExportModelAdmin
to your admin classes.
Basic Usage
1. Add to Django Admin
Import ImportExportModelAdmin
and apply it to your model admin:
from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import MyModel
@admin.register(MyModel)
class MyModelAdmin(ImportExportModelAdmin):
pass
This will automatically add Import and Export buttons in the Django admin.
2. Use Resources for Custom Import/Export Behavior
A Resource
class lets you define the fields and logic for import/export. For example:
Create a resources.py
file:
from import_export import resources
from .models import MyModel
class MyModelResource(resources.ModelResource):
class Meta:
= MyModel
model = ('id', 'name', 'email') # Specify fields to include
fields = ('id', 'name', 'email') # Order of fields export_order
Attach the Resource to the Admin:
from import_export.admin import ImportExportModelAdmin
from .models import MyModel
from .resources import MyModelResource
@admin.register(MyModel)
class MyModelAdmin(ImportExportModelAdmin):
= MyModelResource resource_class
3. Import and Export in Django Admin
- Import: Upload a file (CSV, XLSX, etc.) to create or update records.
- Export: Download the data from the database in the selected format.
File Format Support
By default, Django Import-Export supports: - CSV - JSON - Excel (XLSX) (requires openpyxl
or xlwt
) - YAML - Others (depending on installed libraries).
Install additional libraries for specific formats:
- Excel Support:
bash pip install openpyxl
Customizing Import/Export
Customizing Fields
Exclude or include specific fields using the fields
or exclude
options in the Resource
class:
class MyModelResource(resources.ModelResource):
class Meta:
= MyModel
model = ('password', 'last_login') # Exclude sensitive fields exclude
Custom Import Logic
You can override the before_import
, after_import
, or import_row
methods for custom behavior.
Example: Validate Data Before Import
class MyModelResource(resources.ModelResource):
def before_import_row(self, row, **kwargs):
if not row['email']:
raise ValueError("Email is required.")
Custom Export Logic
You can override the export_queryset
method to export specific subsets of data.
Example: Export Only Active Users
class MyModelResource(resources.ModelResource):
def export_queryset(self, queryset, *args, **kwargs):
return queryset.filter(is_active=True)
Advanced Features
1. Import/Export Specific Columns
Customize the order of fields or include derived fields:
class MyModelResource(resources.ModelResource):
= fields.Field()
full_name
def dehydrate_full_name(self, obj):
return f"{obj.first_name} {obj.last_name}"
class Meta:
= MyModel
model = ('id', 'email', 'full_name') # Include custom fields fields
2. Skip Rows with Errors
Handle errors gracefully without stopping the import:
class MyModelResource(resources.ModelResource):
def import_row(self, row, instance_loader, **kwargs):
try:
return super().import_row(row, instance_loader, **kwargs)
except Exception as e:
print(f"Error importing row {row}: {e}")
return None
3. Handling Relationships
Import/export related fields (e.g., ForeignKey, ManyToMany) by using custom logic.
Example: Import Foreign Keys
class MyModelResource(resources.ModelResource):
= fields.Field(attribute='related_field', column_name='Related Field')
related_field
def before_import_row(self, row, **kwargs):
# Ensure the related object exists
'related_field'] = RelatedModel.objects.get_or_create(name=row['related_field'])[0].id
row[
class Meta:
= MyModel model
4. Export Querysets in Views
Use Django Import-Export to export querysets in views programmatically:
from django.http import HttpResponse
from .resources import MyModelResource
def export_data(request):
= MyModelResource()
resource = resource.export()
dataset = HttpResponse(dataset.csv, content_type="text/csv")
response 'Content-Disposition'] = 'attachment; filename="export.csv"'
response[return response
Error Reporting
Common Errors
Field Does Not Exist: Ensure the fields listed in
fields
orexport_order
match the model fields.Invalid File Format: Make sure the file format matches the library used for import/export.
Foreign Key Issues: Ensure related objects exist before importing data.
Best Practices
Validate Data Before Import: Use the
before_import_row
orclean
method in the model to ensure valid data.Restrict Admin Access: Only allow staff or superusers to use the import/export functionality.
Back Up Data: Always back up the database before performing bulk imports or updates.
Test in Development: Test your import/export process on a development environment before applying to production.
Use Cases
- Importing large datasets (e.g., user data, product catalogs).
- Exporting data for analysis or backup.
- Programmatically updating related models.
- Migrating data between environments or projects.