Django-import-export 未在 Django 管理站点面板中导入具有外键属性的 csv 或 excel 文件

问题描述 投票:0回答:2

我正在 Django 中使用 Django-import-export 模块(版本 4.0.1)。

我有 2 个不同的桌子,名为

State
District

district model
正在使用
state_name
作为
ForeignKey

状态表中的字段可以从

Django admin site panel
导入,没有任何问题,如下所示:

但是无法通过csv/excel文件导入分区属性,错误如下:

Line number: 1 - 'id'
ANDAMAN AND NICOBAR ISLANDS, NICOBARS
Traceback (most recent call last):
File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 667, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 359, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 346, in get_instance
import_id_fields = [
File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 347, in <listcomp>
self.fields[f] for f in self.get_import_id_fields()
KeyError: 'id'

model.py
如下:

from django.db import models

####################################################################################
class State(models.Model):
    state_name = models.CharField(max_length=30)
    
    class Meta:
        db_table = 'State_Names'

    def __str__(self):
        return self.state_name
####################################################################################
class District(models.Model):
    state_name = models.ForeignKey(State, on_delete=models.CASCADE)
    district_name = models.CharField(max_length=30)

    class Meta:
        db_table = 'District_Names'

    def __str__(self):
        return self.district_name

resources.py
如下:

from import_export import fields, resources
from import_export.widgets import ForeignKeyWidget
from damuwhatsapp.models import State
from damuwhatsapp.models import District


class StateResource(resources.ModelResource):
    class Meta:
        model = State

class DistrictResource(resources.ModelResource):
    class StateForeignKeyWiget(ForeignKeyWidget):
        def get_queryset(self, value, row):
            return self.model.objects.filter(
                state_name__exact=row["state_name"],
            )

    state_name = fields.Field(
        column_name='state_name',
        attribute='state_name',
        widget=StateForeignKeyWiget(
            State,
            field='state_name'
        )
    )
    
    district_name = fields.Field(column_name="district_name", attribute="district_name")

    class Meta:
        model = District
        exclude = ('id')
        fields = ('state_name','district_name',)

admin.py
如下:

from django.contrib import admin
from import_export.admin import ImportExportModelAdmin 
from damuwhatsapp.models import State
from damuwhatsapp.models import District
from damuwhatsapp.resources import StateResource
from damuwhatsapp.resources import DistrictResource

class StateAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    resource_class = StateResource
    list_display = ("id", 
                    "state_name")
    search_fields = ["state_name"]
    readonly_fields = ["id"]
    filter_horizontal = ()
    list_filter = ()
    fieldset = ()

class DistrictAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    resource_class = DistrictResource
    list_display = ["id",
                    "state_name",
                    "district_name"]
    search_fields = ("state_name", 
                    "district_name")

    readonly_fields = ["id"]
    
    filter_horizontal = ()
    list_filter = ()
    fieldset = ()

admin.site.register(State, StateAdmin)
admin.site.register(District, DistrictAdmin)

我需要从 Django 管理面板导入具有 District_name 的 csv,该 csv 使用 state_names 作为外键字段。 我已经关注了几个问题,但找不到解决方案。你能看一下代码,看看我哪部分做错了或者需要更改吗? 或者这样做的替代选项是什么。

要导入的CSV文件结构如下。

管理面板:

python-3.x django django-models django-admin django-import-export
2个回答
0
投票

DistrictResource
中,您排除“id”字段并且不声明“import_id_fields” - 因此“district”导入过程无法检测您是否正在导入新实例或现有实例。

您可能想将

import_id_fields = ('state_name','district_name')
添加到
DistrictResource
元声明中。

请参考这个答案


0
投票

在此输入图片描述

数据上传时,数据字段数据不会导入,如下所示。

在此输入图片描述

© www.soinside.com 2019 - 2024. All rights reserved.