Django -用户管理-添加组到list_display

mitkmikd  于 2023-03-31  发布在  Go
关注(0)|答案(2)|浏览(181)

正如我们所知,多对多关系不能在list_display中列出。有没有什么方法可以使它像group1,group2等一样?

bxfogqkk

bxfogqkk1#

奖励:将组显示为用户筛选器:

class SBUserAdmin(UserAdmin):
    list_filter = ("groups")
    list_display = ('username','custom_group', )

    def custom_group(self, obj):
        """
        get group, separate by comma, and display empty string if user has no group
        """
        return ','.join([g.name for g in obj.groups.all()]) if obj.groups.count() else ''

admin.site.unregister(User)
admin.site.register(User, SBUserAdmin)
w1jd8yoj

w1jd8yoj2#

我不明白你的例子(group 1,group 2),但你当然可以使用 * 任何函数 * 作为变更列表视图中的一列,这意味着你可以做你想做的事情!
示例:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('foo', 'bar')

    def foo(self):
        return "This column is Foo"

    def bar(self, obj):
        try:
            return obj.m2m.latest('id')
        except obj.DoesNotExist:
            return "n/a"

    # there's a few more things you can do to customize this output
    def bar(self, obj):
        return '<span style="color:red;">By the way, I am red.</span>'

    bar.short_description = "My New Column Label"
    bar.allow_tags = True

相关问题