[英]Django - how to display related many-to-many field in choice field?
I'm building a web app using Django for my music collection.我正在使用 Django 为我的音乐收藏构建一个网络应用程序。 For each album, there are multiple songs, and each song has one or more composers.
每张专辑都有多首歌曲,每首歌曲都有一个或多个作曲家。 Here's the song model:
这是歌曲模型:
class Song(models.Model):
title = models.CharField(max_length=50)
composer = models.ManyToManyField(Artist)
class Meta:
ordering = ['title']
def __str__ (self):
return self.title
The Artist
model contains firstname
and lastname
fields. Artist
模型包含firstname
和lastname
字段。
There are a number of occurrences of songs with the same title, and the only way to distinguish between them is by the composer.有许多同名歌曲出现,区分它们的唯一方法是作曲家。 Currently, when songs are loaded into a choice field, only the title appears, using
__str__()
method.目前,当歌曲加载到选择字段时,使用
__str__()
方法只显示标题。 I've tried to include the composers, but haven't found a way to make it work.我试图包括作曲家,但还没有找到使它起作用的方法。 Any suggestions?
有什么建议么?
You'll need to somehow insert the composers' names into the Song
's __str__
method.您需要以某种方式将作曲家的名字插入
Song
的__str__
方法中。
One way to do this is by fetching the first and last names of the composers and formatting them before displaying in the __str__
.一种方法是获取作曲家的名字和姓氏,并在显示在
__str__
之前对其进行格式化。 Take the following example:以下面的例子为例:
def __str__(self):
raw_composers = self.composers.values_list("first_name", "last_name")
stringified_composers = [f"{first_name} {last_name}" for (first_name, last_name) in raw_composers]
formatted_composers = ", ".join(stringified_composers)
return f"{self.title} ({formatted_composers})"
While this does work, the Django admin pages that display these choices will be doing lots of queries (namely, N queries for each Song of the list, where N is the amount of Artists related to this song).虽然这确实有效,但显示这些选项的 Django 管理页面将执行大量查询(即,对列表中的每首歌曲进行 N 次查询,其中 N 是与这首歌曲相关的艺术家数量)。 Be sure to run a
.prefetch_related(...)
to speed things up a little!一定要运行一个
.prefetch_related(...)
来加快速度!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.