Skip to content

Commit

Permalink
4 - Aggregate & Annotate
Browse files Browse the repository at this point in the history
  • Loading branch information
codingforentrepreneurs committed Nov 16, 2017
1 parent 50326ef commit 0438bd0
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/analytics/templates/analytics/sales.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ <h1>Sales Data</h1>

<div class='row'>
<div class='col'>
<p>Recent Total: ${{ recent_orders_total }}</p>
<p>Recent Total: ${{ recent_orders_total.total__sum }}</p>
<ol>
{% for order in recent_orders %}
<li>{{ order.order_id }}
Expand Down
18 changes: 13 additions & 5 deletions src/analytics/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count, Sum, Avg
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.shortcuts import render
Expand All @@ -22,11 +23,18 @@ def get_context_data(self, *args, **kwargs):
qs = Order.objects.all()
context['orders'] = qs
context['recent_orders'] = qs.recent().not_refunded()[:5]
recent_orders_total = 0
for i in context['recent_orders']:
recent_orders_total += i.total
context['recent_orders_total'] = recent_orders_total

context['recent_orders_total'] = context['recent_orders'].aggregate(
Sum("total"),
Avg("total"),
# Avg("cart__products__price"),
# Count("cart__products")
)
# context['recent_cart_data'] = context['recent_orders'].aggregate(
# Avg("cart__products__price"),
# Count("cart__products")
# )
# qs = Order.objects.all().aggregate(Sum("total"), Avg("total"), Avg("cart__products__price"), Count("cart__products"))
# ann = qs.annotate(product_avg=Avg('cart__products__price'), product_total = Sum('cart__products__price'), product__count = Count('cart__products'))
context['shipped_orders'] = qs.recent().not_refunded().by_status(status='shipped')[:5]
context['paid_orders'] = qs.recent().not_refunded().by_status(status='paid')[:5]
return context
Binary file modified src/db.sqlite3
Binary file not shown.

0 comments on commit 0438bd0

Please sign in to comment.