Django Import Export Resource Fix
In this tutorial, you'll learn about Django Import Export Resource Fix. We cover key concepts, practical examples, and best practices.
The Problem
Default ModelResource exports all fields and imports with basic validation. When you need custom field mapping, data transformation, or pre/post import hooks, the resource class needs customization.
Quick Fix
Wrong — default resource with no customization
from import_export import resources
class ProductResource(resources.ModelResource):
class Meta:
model = Product
Output: Exports all fields including password hashes, internal IDs, and timestamps. Import accepts empty names and negative prices.
Correct — customized resource
from import_export import resources, fields
from import_export.widgets import DecimalWidget
class ProductResource(resources.ModelResource):
sale_price = fields.Field(
column_name='sale_price',
attribute='sale_price',
widget=DecimalWidget()
)
class Meta:
model = Product
fields = ['id', 'name', 'price', 'sale_price', 'category', 'is_active']
export_order = ['id', 'name', 'price', 'sale_price']
skip_unchanged = True
report_skipped = True
clean_model_instances = True
def dehydrate_price(self, product):
return f"${product.price:.2f}"
def before_import_row(self, row, **kwargs):
row['name'] = row.get('name', '').strip()
if not row['name']:
raise ValueError("Product name is required")
def after_export(self, queryset, data, *args, **kwargs):
data.append_row(['Generated by DodaTech'])
return data
Field deletion policy
class ProductResource(resources.ModelResource):
class Meta:
model = Product
import_id_fields = ['id']
delete_instance_on_conflict = True # Delete if row missing in import
Changing field names for CSV columns
class ProductResource(resources.ModelResource):
class Meta:
model = Product
fields = ['id', 'name', 'price']
column_mappings = {
'Product ID': 'id',
'Product Name': 'name',
'Price (USD)': 'price',
}
def get_export_headers(self):
return ['Product ID', 'Product Name', 'Price (USD)']
Dry run for preview
def preview_import(request):
resource = ProductResource()
dataset = resource.create_dataset(request.FILES['file'])
result = resource.import_data(dataset, dry_run=True)
if result.has_errors():
return Response({
'errors': [str(e.error) for e in result.row_errors()],
})
return Response({
'new': result.totals['new'],
'update': result.totals['update'],
'delete': result.totals['delete'],
'skip': result.totals['skip'],
})
Prevention
- Always specify
fieldsandexport_orderexplicitly. - Use
dehydrate_<field>methods to format export values. - Validate data in
before_import_rowto catch issues early.
Common Mistakes with import export resource
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world DJANGO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro