我正在尝试导出与 Django 内置用户模型具有 OneToOne 关系的 Student。但是当我导出学生时,导出文件中的用户名列是空的。
# models.py
class Student(models.Model):
user = models.OneToOneField(User, verbose_name=_('user'))
student_number = models.CharField(unique=True, null=False, max_length=10, verbose_name=_('student number'))
score = models.PositiveIntegerField(default=0, verbose_name=_('score'))
def __str__(self):
return self.user.get_full_name()
# admin.py
class StudentResource(resources.ModelResource):
username = fields.Field(column_name='username', attribute='User',
widget=widgets.ForeignKeyWidget(model=User, field='username'))
class Meta:
model = Student
fields = ('id', 'username', 'student_number', 'score',)
class StudentAdmin(ImportExportActionModelAdmin):
resource_class = StudentResource
admin.site.register(Student, StudentAdmin)
用这个替换StudentResource
类时我得到结果:
class StudentResource(resources.ModelResource):
class Meta:
model = Student
fields = ('id', 'user__username', 'student_number', 'score',)
但是在导入数据时我会遇到问题。任何想法?