Skip to content

Instantly share code, notes, and snippets.

@benwilber
Created September 2, 2015 02:31
Show Gist options
  • Save benwilber/f2a4211662dac3d32a56 to your computer and use it in GitHub Desktop.
Save benwilber/f2a4211662dac3d32a56 to your computer and use it in GitHub Desktop.
lame groupbys in django
from itertools import groupby
from operator import attrgetter
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=255)
class ItemCountAggregate(models.Model):
item = models.ForeignKey(Item, related_name="count_aggregates")
date = models.DateField()
count = models.PositiveIntegerField()
counts = ItemCountAggregate.objects.order_by("-date", "-count")
groups = groupby(counts, attrgetter("date"))
for date, counts in groups:
print date, list(counts)
# 2015-09-02 [<ItemCountAggregate object>, <ItemCountAggregate object>]
# 2015-09-01 [<ItemCountAggregate object>, <ItemCountAggregate object>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment