Skip to content

Instantly share code, notes, and snippets.

@hossainchisty
Last active December 26, 2021 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hossainchisty/2092b63e76438fe2820fd36f8f7d3f13 to your computer and use it in GitHub Desktop.
Save hossainchisty/2092b63e76438fe2820fd36f8f7d3f13 to your computer and use it in GitHub Desktop.
How to get the total sales of via month in Django
#Note: Let's say we have Sale model total is a field to hold sales amount then we can do like that... we find month via created_at which is DateTimeField.
sales = Sale.objects.all()
months = sales.datetimes('created_at', kind="month")
for month in months:
month_sale = sales.filter(created_at__month=month.month)
month_total = month_sale.aggregate(Sum('total'))['total__sum']
print(f'Month: {month.strftime("%B")} - Total Sale: {month_total}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment