Skip to content

Instantly share code, notes, and snippets.

@harunurkst
Last active November 10, 2020 04:47
Show Gist options
  • Save harunurkst/e1c00562a259847014a90b8ec7f8db8f to your computer and use it in GitHub Desktop.
Save harunurkst/e1c00562a259847014a90b8ec7f8db8f to your computer and use it in GitHub Desktop.
Count number of object created or total number of amount per month in Django
class FundRaisePerMonth(APIView):
def get(self, request):
year = datetime.date.today().year
# Filter data as monthly(number serial) [{'month_serial': views_count} like [{'1': 50, '2': 55}]
queryset = CustomUser.objects.filter(date_joined__year=year)
search = queryset.annotate(month=ExtractMonth('date_joined'),).order_by('month').values('month')\
.annotate(total=Sum('amount')).values('month', 'total')
# convert int month to str month, 1 to January
data = []
for s in search:
s["month"] = calendar.month_name[s["month"]]
data.append(s)
return Response(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment