how to display inline elements in list_display?

我怕爱的太早我们不能终老 提交于 2021-02-19 04:13:30

问题


I have the following problem:

I have two models: Article and Comment, in Comments, i have parent = models.ForeignKey(Article). I have it set up so that Comments is inline to ArticleAdmin(admin.ModelAdmin), and CommentInline(admin.StackedInline). What i would like is that for Article list view (elements chosen in list_display), I would like to display snippets of latest comments so that the user does not have to click into each individual comments to see the changes. Now i know that i can specify a function in list_display, but i'm not sure how to do what i wish to do easily in the functions.

anyone have any suggestion on how to go about accomplishing this?

Thank you very much for your help!


回答1:


As you say, defining a function is the way to go - a custom method on the ModelAdmin class which takes the object as a parameter and returns a string representation of the latest comments:

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('name', 'latest_comments')

    def latest_comments(self, obj):
        return '<br/>'.join(c.comment for c in obj.comment_set.order_by('-date')[:3])
    latest_comments.allow_tags = True

This takes the last three comments on each article, sorted by the 'date' field, and displays the comment field of each one, separated by an HTML <br> tag to show on one each line.



来源:https://stackoverflow.com/questions/3047766/how-to-display-inline-elements-in-list-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!