Last active
December 17, 2015 16:00
-
-
Save AndrewIngram/5636041 to your computer and use it in GitHub Desktop.
Annotations, aggregates and prefetching
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
Two problems: | |
1) Individual annotations can't be filtered | |
2) `prefetch_related` doesn't allow for filtered relations | |
The `annotate()` method is currently used for calculating | |
aggregates for each result in a queryset, but it could be | |
used more generally as an API for attaching the result of | |
some calculation to each model in a queryset - whether it | |
be a single value (an aggregate calculation) or multiple | |
values (a list of models). | |
Curent functionality: | |
Book.objects.annotate(num_authors=Count('authors')) # Attaches a count of each Book's authors to the model as `num_authors` | |
Possible extensions: | |
Book.objects.annotate(num_active_authors=Count('authors').filter(active=True)) # Attaches count of active authors | |
Book.objects.annotate(active_authors=ModelList('authors').filter(active=True)) # Attaches a list of active author instances | |
Is this possible? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment