You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django import-export导入异常:仅生成ID,名称和描述未导入

问题排查

  1. CSV缺少表头导致字段映射失败:你的CSV文件没有表头行,django-import-export无法识别每一列对应模型的哪个字段,导致name和description数据无法匹配到对应字段,仅自动生成ID。
  2. Resource字段与CSV列数不匹配:CategoryResource定义了('id', 'name', 'description',)三个字段,但CSV每行有4个值(末尾两个空值对应parent字段),字段数量不匹配进一步加剧了映射异常。

解决方法

方案一:修改CSV文件(最直接)

给CSV添加表头行,且去掉每行末尾多余的逗号,让列与CategoryResource定义的字段对应:

name,description
eCommerce,A website for online buying and selling products
Business,A website for promoting and conducting business activities
Blog,A website for publishing articles stories and posts
Portfolio,A website showcasing an individual's or organization's work
Event,A website for promoting and managing events
Personal,A personal website for individuals to share their interests and content
Membership,A website with restricted access for members only
Nonprofit,A website for nonprofit organisations to promote their cause

注:不需要包含id列,因为ID由系统自动生成;如果需要导入parent字段,可在表头添加parent列并填写父分类的名称或ID。

方案二:调整CategoryResource配置(适配原有CSV格式)

如果不想修改CSV,可调整Resource配置,移除不需要的id字段,并指定字段顺序:

class CategoryResource(resources.ModelResource):
    class Meta:
        model = Category
        # 只保留需要导入的字段,顺序与CSV列对应
        fields = ('name', 'description',)
        skip_unchanged = True
        report_skipped = False

导入时在Admin界面选择**"按顺序匹配列"**选项,系统会按照fields的定义顺序对应CSV的列。


扩展:导入带父分类的CSV(可选)

如果需要导入包含父分类的数据,可给Resource添加parent字段的转换器:

from import_export.fields import Field
from import_export.widgets import ForeignKeyWidget

class CategoryResource(resources.ModelResource):
    parent = Field(
        column_name='parent',
        attribute='parent',
        # 通过父分类的name字段匹配关联
        widget=ForeignKeyWidget(Category, 'name')
    )
    
    class Meta:
        model = Category
        fields = ('name', 'description', 'parent',)

对应的CSV格式示例:

name,description,parent
eCommerce,A website for online buying and selling products,
SubShop,Sub category of eCommerce,eCommerce

内容的提问来源于stack exchange,提问作者crawlingdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:20:21