Skip to content

Django Import Export Resource Fix

DodaTech Updated 2026-06-24 2 min read

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 fields and export_order explicitly.
  • Use dehydrate_<field> methods to format export values.
  • Validate data in before_import_row to catch issues early.

Common Mistakes with import export resource

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. 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

### What is dehydrate used for?

dehydrate_<fieldname> transforms values during export. For example, formatting currency or converting boolean to yes/no.

What is the difference between import_id_fields and skip_unchanged?

import_id_fields identifies existing records for update. skip_unchanged skips rows that haven't changed.

Can I have multiple resources per model?

Yes. Create different resource classes for different export formats or permission levels (admin vs user).

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro