Django - 在admin list_display函数中包含来自foreignkey的数据 [英] 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"]
我想显示list_display中的人的朋友。我知道如果我在 Person
模型中有外键字段,我可以使用双下划线来引用它。 person2__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.
在我的系统中,一个人一次只能和一个人交朋友,如果外键在人物模型中,但是我想要存储关于友谊的额外信息,如制作日期(firendship_made),那么这就是为什么我把它放在一个单独的模型中。任何建议?如果我不得不改变我的模型以获得最好的结果,我不介意。
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.
推荐答案
你需要创建一个这样的东西在你的FriendAdmin类中:
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'
这篇关于Django - 在admin list_display函数中包含来自foreignkey的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!