是否可以通过 Django 中的单个查询获取所有作者

Is it possible to get all authors by single query in django

class Author(models.Model):
    name = models.CharField(max_length=50)

class Chapter(models.Model):
    book = models.ForeignKey(Album, on_delete=models.CASCADE)
    author = models.ManyToManyField("Author")

class Book(models.Model):
    author = models.ManyToManyField("Author")

我试图在访问一个作者详细信息时显示所有相关作者。为此,我目前这样做是为了实现这一点:

authors = []
for chapter in Author.objects.get(id=id).chapter_set.all():
    authors.append(chapter.artists.all())

djangoORM

有没有其他方法可以做到这一点

您可以在过滤器中向后遵循 ManyToManyField 关系,在 Author 模型的情况下,您应该能够使用 chapter__ 访问 Chapter.author 关系

authors = Author.objects.filter(chapter__author_id=id).distinct()