Skip to content

Instantly share code, notes, and snippets.

@christherama
Last active July 20, 2023 15:11
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 christherama/d4b9489c3f357315abcd1c66476e0520 to your computer and use it in GitHub Desktop.
Save christherama/d4b9489c3f357315abcd1c66476e0520 to your computer and use it in GitHub Desktop.
Django query with aggregation
status_counts_by_month = (
Task.objects.filter(plan_id=plan_id, metric_type=metric_type, group_by_date__year=effective_year)
.annotate(
completed_on_time=Case(
When(completed_date__isnull=True, then=0),
When(completed_date__lte=F("due_date"), then=1),
default=0,
output_field=IntegerField(),
)
)
.annotate(month=ExtractMonth("group_by_date"))
.values("month")
.annotate(total=Count("id"), number_completed_on_time=Sum("completed_on_time"))
.values("month", "number_completed_on_time", "total")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment