Skip to content

Django Import Export Foreign Key Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Django Import Export Foreign Key Fix. We cover key concepts, practical examples, and best practices.

The Problem

Importing CSV with foreign key fields fails because the CSV contains category names, not IDs. Without ForeignKeyWidget, django-import-export doesn't know how to resolve the relationship.

Quick Fix

Wrong — importing FK as plain text

from import_export import resources

class ProductResource(resources.ModelResource):
    class Meta:
        model = Product
        fields = ['name', 'category']  # category is a FK

Output: Import tries to set category = "Electronics" as a string on a FK field. IntegrityError or validation error.

Correct — ForeignKeyWidget

from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget
from .models import Product, Category

class ProductResource(resources.ModelResource):
    category = fields.Field(
        column_name='category',
        attribute='category',
        widget=ForeignKeyWidget(Category, 'name')  # Look up by name
    )

    class Meta:
        model = Product
        fields = ['id', 'name', 'price', 'category']

Output: CSV with category name "Electronics" resolves to the Category instance, even if the ID is different.

Multiple lookup fields

# Custom widget for composite lookup
from import_export.widgets import Widget

class CategorySlugWidget(Widget):
    def clean(self, value, row=None, *args, **kwargs):
        return Category.objects.get(
            name=row.get('category_name'),
            slug=value
        )

    def render(self, value, obj=None):
        return obj.category.slug if obj and obj.category else ''

Handling nullable FK

category = fields.Field(
    column_name='category',
    attribute='category',
    widget=ForeignKeyWidget(Category, 'name'),
    default=None,  # Null if not provided
    saves_null_values=True,
)
class ProductResource(resources.ModelResource):
    category = fields.Field(
        column_name='category',
        attribute='category__name',  # Export category name, not ID
        widget=Widget()
    )

    class Meta:
        model = Product

ManyToMany fields

from import_export.widgets import ManyToManyWidget

tags = fields.Field(
    column_name='tags',
    attribute='tags',
    widget=ManyToManyWidget(Tag, field='name', separator=',')
)

Output: CSV column tags accepts comma-separated values: python,django,tutorial.

Prevention

  • Always use ForeignKeyWidget for FK fields in import/export resources.
  • Specify the lookup field (usually name or slug) — not the default pk.
  • Test imports with a sample CSV that includes related model records.

Common Mistakes with import export foreign key

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

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 happens if the FK value doesn't exist in the database?

ForeignKeyWidget raises an error. You can handle it in before_import_row() by creating missing related objects.

Can I import by multiple FK fields?

Use a custom Widget that implements clean() to look up by multiple fields.

Does ForeignKeyWidget work for export too?

Yes. It renders the related object's field value (e.g., category name) in the exported file.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro