How to display inline elements in list_display?

I have the following problem:

I have two models: article and comment, in the comments, I have parent = models.ForeignKey (article). I configured it so that comments are embedded in ArticleAdmin (admin.ModelAdmin) and CommentInline (admin.StackedInline). I would like to view a list of articles (items selected in list_display), I would like to display fragments of the latest comments so that the user could not click on each individual comment 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 want to do easily in functions.

Anyone have any suggestions on how to do this?

Many thanks for your help!

+3
source share
1 answer

As you say, a function definition is the path to a user method of the ModelAdmin class, which takes an object as a parameter and returns a string representation of the last 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 for each article, sorted by date field, and displays commenteach field separated by an HTML tag <br>to display on each line.

+3
source

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


All Articles