Skip to content

Instantly share code, notes, and snippets.

@Martin91
Last active August 10, 2018 07:36
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 Martin91/5536d1909204e4c3f57a61644c372e96 to your computer and use it in GitHub Desktop.
Save Martin91/5536d1909204e4c3f57a61644c372e96 to your computer and use it in GitHub Desktop.
django work with aggregation functions
from django.db.models import Count
Model.values('pickup_plan_id').annotate(picked_count=Count('pickup_plan_id')).filter(picked_count__lt=2)
# SELECT
# `model`.`pickup_plan_id`,
# COUNT(`model`.`pickup_plan_id`) AS `picked_count`
# FROM
# `model`
# WHERE
# `model`.`pickup_id` = 870001
# GROUP BY
# `model`.`pickup_plan_id`
# HAVING COUNT(`model`.`pickup_plan_id`) < 2
# ORDER BY NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment