fix: InvoiceQuerySet.annotate_total() (but for real this time)

This commit is contained in:
imperosol 2024-10-13 10:37:48 +02:00
parent 768e2867b5
commit 564d95f701
2 changed files with 4 additions and 4 deletions

View File

@ -158,10 +158,11 @@ def test_user_invoice_with_multiple_items():
item_recipe = Recipe(InvoiceItem, invoice=foreign_key(Recipe(Invoice, user=user))) item_recipe = Recipe(InvoiceItem, invoice=foreign_key(Recipe(Invoice, user=user)))
item_recipe.make(_quantity=3, quantity=1, product_unit_price=5) item_recipe.make(_quantity=3, quantity=1, product_unit_price=5)
item_recipe.make(_quantity=1, quantity=1, product_unit_price=5) item_recipe.make(_quantity=1, quantity=1, product_unit_price=5)
item_recipe.make(_quantity=2, quantity=1, product_unit_price=iter([5, 8]))
res = list( res = list(
Invoice.objects.filter(user=user) Invoice.objects.filter(user=user)
.annotate_total() .annotate_total()
.order_by("-total") .order_by("-total")
.values_list("total", flat=True) .values_list("total", flat=True)
) )
assert res == [15, 5] assert res == [15, 13, 5]

View File

@ -173,9 +173,8 @@ class InvoiceQueryset(models.QuerySet):
return self.annotate( return self.annotate(
total=Subquery( total=Subquery(
InvoiceItem.objects.filter(invoice_id=OuterRef("pk")) InvoiceItem.objects.filter(invoice_id=OuterRef("pk"))
.annotate(item_amount=F("product_unit_price") * F("quantity")) .values("invoice_id")
.values("item_amount") .annotate(total=Sum(F("product_unit_price") * F("quantity")))
.annotate(total=Sum("item_amount"))
.values("total") .values("total")
) )
) )