问题
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