如何在 Django admin `list_display` 中显示外键和多对多字段?

时间:2021-04-11 09:47:36

标签: django django-admin

如何在 Django admin list_display 中显示外键和多对多字段?

models.py:

class Book(models.Model):
    title = models.CharField(max_length=150, blank=False)

class Character(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='character')
    name = models.CharField(max_length=50)

class Author(models.Model):
    book = models.ManyToManyField(Book, related_name='author')
    name = models.CharField(max_length=50)

admin.py:

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'characters', 'authors')

    def characters(self, obj):
        ???

    def authors(self, obj):
        ???

1 个答案:

答案 0 :(得分:1)

您可以获取相关的 characters/authors,然后将名称加入逗号分隔列表中:

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'characters', 'authors')

    def characters(self, obj):
        return ', '.join([c.name for c in obj.character.all()])

    def authors(self, obj):
        return ', '.join([a.name for a in obj.author.all()])

我们可以通过使用 .prefetch_related(…) [Django-doc] 批量获取所有相关对象来提高性能:

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'characters', 'authors')

    def characters(self, obj):
        return ', '.join([c.name for c in obj.character.all()])

    def authors(self, obj):
        return ', '.join([a.name for a in obj.author.all()])

    def get_queryset(self, request):
        return super().get_queryset(request).prefetch_related(
            'character', 'author'
        )

由于 related_name 是反向关系,并且可以有 multiple Characters/Authors,所以给这些一个 < em>复数名称。