Created
September 2, 2015 02:31
-
-
Save benwilber/f2a4211662dac3d32a56 to your computer and use it in GitHub Desktop.
lame groupbys in django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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