ORM左连接查询和总和

时间:2014-08-21 22:41:17

标签: django django-views

我想选择所有发布者和相关书籍(如果存在),即sql left join。然后我想用出版商的图书价格和打印项目的报告。这样做的最佳方式是什么?

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

class Book(models.Model):
   name = models.CharField(max_length=50)
   publisher = models.ForeignKey(Publisher)
   price = models.DecimalField(max_digits=10, decimal_places=2)

期望的结果:

PublisherA [150]
---Book1 [100]
---Book2 [50]
PublisherB [0]
---<none>
PublisherC [25]
---Book3 [25]
Total [175] 

1 个答案:

答案 0 :(得分:0)

我没有对此进行过测试,但请尝试:

查看

from django.db.models import Sum
Publisher.objects.annotate(book_price_sum=Sum('book__price'))

<强>模板

{% for publisher in publishers %}
    Sum of book prices: {{ publisher.book_price_sum }}
    {% for book in publisher.book_set %}
        {{ book.name }}: {{ book.price }}
    {% endfor %}
{% endfor %}