请考虑以下两个模型,Worker
和Invoice
:
class Worker(models.Model):
name = models.CharField(max_length=255)
class Invoice(models.Model):
worker = models.ForeignKey(
'Worker', on_delete=models.CASCADE)
amount = models.DecimalField(max_digits=10, decimal_places=2)
我只想对给定Invoice
的总数(amount
的总数)大于零的Worker
进行查询。
基本上,我想定义一个get_payable_invoices()
函数,该函数返回一个Queryset
以便测试通过:
from decimal import Decimal
from django.test import TestCase
from django.db.models import Sum
from myapp.models import Worker, Invoice
def get_payable_invoices():
return Invoice.objects.filter(
worker__in=Worker.objects.annotate(Sum('invoice__amount')))\
.filter(invoice__amount__sum__gt=0)
class PayableInvoicesTests(TestCase):
def test_get_payable_invoices(self):
worker1 = Worker.objects.create(name="John Doe")
invoice1 = Invoice.objects.create(
worker=worker1, amount=Decimal('100.00'))
invoice2 = Invoice.objects.create(
worker=worker1, amount=Decimal('-150.00'))
worker2 = Worker.objects.create(name="Mary Contrary")
invoice3 = Invoice.objects.create(
worker=worker2, amount=Decimal('200.00'))
self.assertEqual(get_payable_invoices().count(), 1)
self.assertEqual(get_payable_invoices().first(), invoice3)
但是当前的实现无法正常工作,并返回一个
django.core.exceptions.FieldError: Cannot resolve keyword 'invoice' into field. Choices are: amount, id, worker, worker_id
看来,尽管遍历查询集时返回的对象确实具有invoice__amount__sum
属性,但是不能以这种方式在filter()
中使用它。
在我看来,我应该按照https://docs.djangoproject.com/en/2.2/ref/models/expressions/#using-aggregates-within-a-subquery-expression中的查询语句来制定查询条件,但由于total_comments
返回一个数字,而我却难以适应该示例。想要Worker
的列表。我也不完全确定子查询是否是正确的方法,或者如果没有它们,是否可以通过更简单的方式完成。关于如何在Django中实现这种查询的任何想法?
答案 0 :(得分:1)
从https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#filtering-on-annotations可以看出,在过滤注释时,您需要使用不同于默认名称的名称来“消除歧义”。以下功能使测试通过:
def get_payable_invoices():
return Invoice.objects.filter(
worker__in=Worker.objects
.annotate(invoice_total=Sum('invoice__amount'))
.filter(invoice_total__gt=0))
我还验证了是否执行了一个查询。例如,我可以将以下内容添加到单元测试的底部:
with self.assertNumQueries(1):
for invoice in get_payable_invoices():
pass