Django - including 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 a friend to the person in the display_list. I know if I had a foreignkey field in the model Person, I could use double underscore to refer to it, for example. person2__surname. But not sure how to do this when the foreign key is in another table.

In my system, one person can only be friends with one person at a time, so it would be better if the foreign key was in the person’s model, but I want to store additional information about the friendship, such as the date it was created (firendship_made), so I placed it in a separate model. Any recommendations? If I need to change my models to get the best result, I do not mind.

+3
3

- FriendAdmin:

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

    def get_reviews(self, obj):
        return obj.book.review
    get_reviews.short_description = 'Review'
+7

- ForeignKeys Friends Person, related_name . , .

, OneToOneField, ForeignKey. my_person.friend1.person1.surname, my_person - , , friend1 - related_name, .

0

Thans for your answer uvasal ( ),

you need: return '% s'% (obj.book.review,) or return '% s'% obj.book.review

0
source

Source: https://habr.com/ru/post/1771280/


All Articles