Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Give example of annotate function on querysets #9

Open
raiderrobert opened this issue Jan 3, 2017 · 1 comment
Open

Give example of annotate function on querysets #9

raiderrobert opened this issue Jan 3, 2017 · 1 comment

Comments

@raiderrobert
Copy link

raiderrobert commented Jan 3, 2017

One of the most powerful reducer for extra queries that I discovered was the annotate function. For example:

# in models.py
from django.db import models


class Artist(models.Model):
    name = models.CharField(max_length=250)


class Album(models.Model):
   artist = models.ForeignKey(Artist)
   title = models.CharField(max_length=250)
   published = models.DateField()
  


# in views.py
from django.views.generic import ListView
from .models import Artist


class ArtistList(ListView):
    """
    Common set of fields
    """
    model = Artist
    def get_queryset(self):
        queryset = super(ArtistList, self).get_queryset()
        return queryset.annotate(most_recent=Max('album__published')).order_by('-most_recent')


This results in a single query. A person who was unaware of this function may be tempted to use a list comprehension to loop through the albums for each artist in display.

@natecox
Copy link

natecox commented Jan 4, 2017

Is QuerySet#annotate not covered in Two Scoops? I could have sworn there was an example in there somewhere. If not, it's certainly worth mentioning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants