Reputation: 85
I have a participant model in models.py Django as the following:
from django.db import models
from django.contrib.auth.models import User
class Participant(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
score = models.FloatField(default=0)
completed_study = models.BooleanField(default=False)
def __str__(self):
return self.user.username
and I want to be able to export all the data from the admin page, so under the admin.py I added the following
from django.contrib import admin
from .models import Participant
from django.contrib.auth.admin import UserAdmin as BaseAdmin
from import_export.admin import ImportExportModelAdmin
from import_export import resources
from django.contrib.auth.models import User
class UserResource(resources.ModelResource):
class Meta:
model = User
fields = ('id', 'username')
class UserAdmin(BaseAdmin, ImportExportModelAdmin):
resource_class = UserResource
class ParticipantAdmin(admin.ModelAdmin):
list_display = ['user', ]
readonly_fields = ('created_at', 'updated_at',)
class ParticipantAdmin(ImportExportModelAdmin):
pass
admin.site.register(Participant, ParticipantAdmin)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
I am able to export the data from the participant model, but I want under the user field to display the actual username rather than the id. How can I do that? is that even doable?
Upvotes: 0
Views: 55
Reputation: 85
I just had to add:
fields = ('user__username')
to represent the relational field
Upvotes: 0
Reputation: 3941
class UserResource(resources.ModelResource):
class Meta:
model = User
fields = ('id', 'username')
def dehydrate_username(self, user):
return user.username
The import-export library provides a dynamic method based on relation fields so you can return data whatever you want for specific field using dehydrate_<field>
Upvotes: 1