我正在尝试将数据导入到我的某个模型中,但它失败了,因为我正在尝试上传foreignKey Id,而不是导入导出创建的迭代数字。
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
我的admin.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
id, name, school_id, Al1EOC, AL2EOC
,'Main st school', 1238008, 12.9, 14.9
当我从SOL模型导出数据时,我得到学校ID的迭代编号。我想要实际的学校ID - 持有foreignKey关系的那个。然后,我需要使用该foreignKey号上传数据。我知道ForeignKey小部件就是这样做的,但我不明白它是如何实现的。
答案 0 :(得分:4)
文档中有ForeignKeyWidget。你可以在这里使用它。还有IntegerWidget和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)
这是一个有效的例子。希望它会有所帮助。
答案 1 :(得分:3)
我认为这会有所帮助:
class SolResource(resources.ModelResource):
school_id = fields.Field()
class Meta:
# ...
def dehydrate_school_id(self, sol):
return sol.school_id.school_id # You can get all fields of related model. This is example.
答案 2 :(得分:3)
使用小工具很棒。
school_id = fields.Field(column_name='school_id', attribute='Sol', widget=widgets.ForeignKeyWidget(Sol, 'school_id'))