【问题标题】:Django - annotate on multiple fields and load relevant objectsDjango - 在多个字段上注释并加载相关对象
【发布时间】:2020-07-28 15:21:43
【问题描述】:

假设我有以下模型

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

class Publisher(models.Model):
    name = models.CharField(max_length=25)
    ...

class Book(models.Model):
    author = models.ForeignKey(Author)
    publisher = models.ForeignKey(Publisher)
    ...

由于某种原因,我想查询作者和出版商的书籍和分组结果,所以:

books = Book.objects.values('author', 'publisher').annotate('sth'=Avg('sth_else'))

结果如下:

<BookQuerySet [{'author': 2, 'publisher': 1, 'sth': 1.0}]>

是否可以加载整个 Author 和 Publisher 对象,而不仅仅是它们的相关 id?

【问题讨论】:

    标签: django django-orm


    【解决方案1】:

    恐怕不是。为了得到各自的作者和出版者对象。您可能只需要使用从查询中获得的 id 并进行另一个查询。

    authors = Author.objects.filter(id__in = authors)
    publishers = Publisher.objects.filter(id__in = publishers)
    
    

    authors,publishers 是您在上面得到的 id 列表

    【讨论】:

      猜你喜欢
      • 2013-12-07
      • 1970-01-01
      • 2020-09-03
      • 2013-10-30
      • 1970-01-01
      • 2017-05-05
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多