Skip to content

Instantly share code, notes, and snippets.

@lcruz
Created May 4, 2012 15:15
Show Gist options
  • Save lcruz/2595418 to your computer and use it in GitHub Desktop.
Save lcruz/2595418 to your computer and use it in GitHub Desktop.
Group a list of objects (django model) by a foreign model
def group_by_foreign_model():
"""
Example of the model:
class MyModel(Model):
foreign = models.ForeignKey(MyForeignModel)
"""
result = MyModel.objects.all()
# key is the ID foreign model
values = sorted(result, key=lambda x:x.foreign.id)
# key is the foreign model
return [(x,list(y)) for x,y in itertools.groupby(values, key=lambda x:x.foreign)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment