Django Import Export Foreign Key Fix
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,
)
Export with related fields
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
nameorslug) — not the defaultpk. - Test imports with a sample CSV that includes related model records.
Common Mistakes with import export foreign key
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro