You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
The text was updated successfully, but these errors were encountered:
One of the most powerful reducer for extra queries that I discovered was the annotate function. For example:
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.
The text was updated successfully, but these errors were encountered: