Created
May 4, 2012 15:15
-
-
Save lcruz/2595418 to your computer and use it in GitHub Desktop.
Group a list of objects (django model) by a foreign model
This file contains 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
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