Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Include data from foreignkey in admin list_display function

I have two models and one admin model:

class Person(models.Model):

    firstname = models.CharField(maxlength=50)
    surname = models.CharField(maxlength=50)

class Friends(models.Model):

    person1 = models.ForeignKey("Person")
    person2 = models.ForeignKey("Person")
    friendship_made = models.DateField()

class PersonAdmin(admin.ModelAdmin):
    list_display = ["firstname", "surname"]

I want to show the friend of the person in the list_display. I know if I had the foreignkey field in the Person model I could use the double underscore to reference it e.g. person2__surname. But not sure how to do it when thr foreign key is in the other table.

In my system one person can only be friends with one person at a time so it would be better if the foreignkey was in the person model but I want to store extra info about the friendship such as the date it was made (firendship_made) so this is why I've put it in a seperate model. Any advise? If I have to change my models to get the best result I don't mind.

like image 290
John Avatar asked Jan 22 '23 05:01

John


1 Answers

You need to create something like this in your FriendAdmin class:

class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_reviews')

    def get_reviews(self, obj):
        return obj.book.review
    get_reviews.short_description = 'Review'
like image 107
dan-klasson Avatar answered Jan 25 '23 15:01

dan-klasson