Django admin field. get value in relation field

Viewed 329

Models.py

class Student(models.Model):
    first_name = models.CharField(max_length=255)

class Room(models.Model):
    room_name = models.CharField(max_length=20)
    student = models.OneToOneField(Student, on_delete=models.CASCADE)

Admin.py

class RoomAdmin(admin.ModelAdmin):
    model = Room
    fields = ('room_name', 'student__first_name',)

I need to appear field "first_name" on add room admin page. So i set admin follow source code, I recived errors.

ERRORS:
<class 'building.admin.RoomAdmin'>: (admin.E108) The value of 'fields[1]' refers to 'student__first_name', which is not a callable, an attribute of 'RoomAdmin', or an attribute or method on 'building.Room'.

Please guide or suggess for this thank you :)

1 Answers

As the error indicates, the student__first_name is not a field of Room class. In such situations, you can define a callable function as,

class RoomAdmin(admin.ModelAdmin):
    model = Room
    fields = ('room_name', 'first_name',)

    def first_name(self, room):
        return room.student.first_name
Related