如何在list_display中显示内联元素? [英] how to display inline elements in list_display?

查看:46
本文介绍了如何在list_display中显示内联元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

我有两个模型:Article和Comment,在Comments中,我有parent = models.ForeignKey(Article).我进行了设置,以使Comment内联到ArticleAdmin(admin.ModelAdmin)和CommentInline(admin.StackedInline).我想要的是文章列表"视图(在list_display中选择的元素),我想显示最新评论的摘要,以便用户不必单击每个单独的评论即可查看更改.现在我知道我可以在list_display中指定一个函数,但是我不确定如何在这些函数中轻松完成我想做的事情.

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?

非常感谢您的帮助!

推荐答案

正如您所说,定义函数是必经之路-ModelAdmin类上的自定义方法,该方法将对象作为参数并返回的字符串表示形式.最新评论:

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

这将获取每篇文章的最后三个注释,并按日期"字段排序,并显示每个注释的 comment 字段,并用HTML < br> 标记以每行显示一次.

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.

这篇关于如何在list_display中显示内联元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆