1

I'm trying to export Student, which has a OneToOne relationship with Django built-in User model. But when I export Students, the username column is empty in the exported file.

# 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)

I get result when replace StudentResource class with this:

class StudentResource(resources.ModelResource):

    class Meta:
        model = Student
        fields = ('id', 'user__username', 'student_number', 'score',)

but then I would have problem when importing data. Any idea?

1 Answer 1

3

Well, it is about the capitalized 'User' in attribute='User' in username field. I thought it might be good to explain more about using ForeignKeyWidget.

To use ForeignKeyWidget you should specify these elements:

  • Specify a column_name which is the name of the column in your import/export file.
  • In attribute, determine the name of the field of your current model, which is a OneToOneField or a ForeignKey. In my case it is user in Student model.
  • In ForeignKeyWidget specify the name of related model and one of its fields which you want to get data from. In my case the related model is User and the field is its username field.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for this answer. Your explanation is better than the official django-import-export documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.