What's the difference between select_related and prefetch_related in Django?


Django tip:

Select_related vs prefetch_related

  • Use select_related() on OneToOneField or ForeignKey when you need a single object
  • Use prefetch_related() on ManyToManyFields or reverse relations when you need many objects

👇

class Singer(models.Model):
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)


class Song(models.Model):
    name = models.CharField(max_length=100)
    singer = models.ForeignKey(Singer, related_name="songs")


Song.objects.select_related("singer").all()  # Forward ForeignKey relationship
Singer.objects.select_related("song").all()  # Backward ForeignKey relationship