Issue
How to display the foreign key and many-to-many fields in 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):
???
Solution
You can fetch the related character
s/author
s and then join the names in a comma separated list:
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()])
We can boost performance by using .prefetch_related(…)
[Django-doc] to fetch all related objects in bulk:
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'
)
Since the related_name
is the relation in reverse, and there can be multiple Character
s/Author
s, it makes sense to give these a plural name.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.