将ForeignKey小部件添加到django-import-export [英] Adding foreignKey widget to django-import-export

查看:118
本文介绍了将ForeignKey小部件添加到django-import-export的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据导入到我的一个模型中,但是失败了,因为我正在尝试上载foreignKey ID,而不是import-export创建的迭代数字.

I'm trying to import data to one of my models, but it's failing because I'm trying to upload the foreignKey Id, not the iterated number that import-export creates.

models.py

models.py

from django.db import models
from import_export import resources


class School(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=100)
    school_id = models.IntegerField(unique=True)

class Sol(models.Model):
    school_id = models.ForeignKey(School, to_field='school_id')
    name = models.CharField(max_length = 100)
    Al1EOC = models.DecimalField(max_digits=5, decimal_places=2)
    AL2EOC = models.DecimalField(max_digits=5, decimal_places=2)

#Class for django-import-export
class SolResource(resources.ModelResource):
    class Meta:
        model = Sol

我的管理员.py

from import_export.admin import ImportExportModelAdmin


class SolAdmin(ImportExportModelAdmin):
    list_display = ('name', 'school_id')
    resources_class = SolResource
    pass

admin.site.register(Sol, SolAdmin)

我的data.csv

My data.csv

id, name, school_id, Al1EOC, AL2EOC
,'Main st school', 1238008, 12.9, 14.9

当我从SOL模型中导出数据时,我得到了学校ID的重复编号.我想要实际的School ID-拥有ForeignKey关系的那个ID.并且,随后,我需要使用该foreignKey号上传数据.我知道ForeignKey小部件是执行此操作的方法,但我不知道它是如何实现的.

When I export the data from the SOL model, I get an iterated number for the school ID. I want the actual School ID - the one that holds the foreignKey relationship. And, subsequently, I need to upload data with that foreignKey number. I know the ForeignKey widget is the way to do it, but I don;t understand how it is implemented.

推荐答案

There is ForeignKeyWidget in the documentation. You can use it here. There are also IntegerWidget and DecimalWidget.

from import_export.admin import ImportExportModelAdmin

class SolResource(resources.ModelResource):
    school_id = fields.Field(
        column_name='school_id',
        attribute='school_id',
        widget=ForeignKeyWidget(School, 'name'))

    class Meta:
        model = Sol

class SolAdmin(ImportExportModelAdmin):
    list_display = ('name', 'school_id')
    resources_class = SolResource

admin.site.register(Sol, SolAdmin)

这是一个有效的示例.希望对您有所帮助.

This is a working example. Hope it will help.

这篇关于将ForeignKey小部件添加到django-import-export的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆