将外键添加到 Django 导入导出

时间:2021-04-28 05:05:37

标签: django django-models django-admin django-import-export

我正在尝试使用 Django_Import Export 从 csv 导入数据。我看到了其他 SO 帖子,但他们没有帮助。以下是模型

模型.py

class TblSubject(amdl.AagamBaseModel):
    subject_id = models.AutoField(primary_key=True)
    subject_name = models.CharField(max_length=20)
    standard = models.ForeignKey('TblStandard', models.DO_NOTHING)
    remembrance_credit = models.IntegerField(default=40)
    applied_knowledge_credit = models.IntegerField(default=30)
    understanding_credit = models.IntegerField(default=30)
    subject_credit = models.IntegerField(default=100)

    class Meta:
        db_table = 'tblsubject'

    def __str__(self):
        return f'{self.subject_name}'


class SubjectChapter(amdl.AagamBaseModel):
    subject_chapter_id = models.AutoField(primary_key=True)
    subject = models.ForeignKey('TblSubject', on_delete=models.CASCADE)
    chapter_id = models.IntegerField()
    chapter_name = models.CharField(max_length=150)
    remembrance_credit = models.IntegerField()
    applied_knowledge_credit = models.IntegerField()
    understanding_credit = models.IntegerField()
    chapter_credit = models.IntegerField()

    class Meta:
        db_table = 'subject_chapter'

    def __str__(self):
        return f'{self.chapter_id} {self.chapter_name} : {self.subject}'

这里是admin.py

from django.contrib import admin
from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget
from .models import SubjectChapter, TblSubject
from import_export.admin import ImportExportModelAdmin


class SubjectChapterResource(resources.ModelResource):
    class Meta:
        model = SubjectChapter
        import_id_fields = ('subject_chapter_id',)
        subject = fields.Field(
            column_name='subject_name',
            attribute='subject_name',
            widget=ForeignKeyWidget(TblSubject, 'subject_id'))


class SubjectChapterAdmin(ImportExportModelAdmin):
    resource_class = SubjectChapterResource


admin.site.register(SubjectChapter, SubjectChapterAdmin)

我收到以下错误

enter image description here

我正在从 csv 插入 SUBJECTCHAPTER 的数据,其中 SUBJECT 列是来自 TBLSUBJECT 的外键,它包含 TBLSUBJECT 的名称。

1 个答案:

答案 0 :(得分:0)

改变这个

class SubjectChapterResource(resources.ModelResource):
    class Meta:
        model = SubjectChapter
        import_id_fields = ('subject_chapter_id',)
        subject = fields.Field(
            column_name='subject_name',
            attribute='subject_name',
            widget=ForeignKeyWidget(TblSubject, 'subject_name'))

subject_idsubject_name

相关问题