0

I have a simple situation with two models and a ForeignKey:

class Image(models.Model):
   # Stuff here

   def iotd_date(self):
       iotd = self.image_of_the_day.all()
       if iotd: 
          return iotd[0].date
       return None

class ImageOfTheDay(models.Model):
   date = models.DateField()
   image = models.ForeignKey(Image, related_name = 'iotd')

Whenever I do {{some_image.iotd_date}} in a template, that hits the database.

How can I prefetch that information? I've tried .select_related('iotd') (the related_name) but it didn't work.

Salvatore Iovene
  • 2,064
  • 1
  • 17
  • 31

1 Answers1

0

I've found out: prefetch_related does the trick, actually.

Salvatore Iovene
  • 2,064
  • 1
  • 17
  • 31