# models.py
class Gallery(models.Model):
images = models.ManyToManyField(Image, null=True, blank=True)
class Image(models.Model):
image = models.ImageField()
# views.py
class GalleryIndex(ListView):
model = Gallery
I need to get thumbnail for every gallery, which is it’s very first/last/whatever image.
How can I LIMIT image by 1 for any gallery as a custom attribute (to not override Gallery.images) without calling second SQL query?
I should’ve read docs better. Standard QuerySet API can’t handle such cases efficiently (
annotate()generatesGROUP BYclause for each of parent fields which is slow) so I come withextra()method and raw subquery.This queryset do exactly what I wanted, since SorlImageField (and ImageField) needs only filename to represent thumbnail in templates.