Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Last active December 17, 2015 16:00
Show Gist options
  • Save AndrewIngram/5636041 to your computer and use it in GitHub Desktop.
Save AndrewIngram/5636041 to your computer and use it in GitHub Desktop.
Annotations, aggregates and prefetching
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