Find all N+1 violations in your Django app

The N+1 problem is a common database performance issue. It plagues ORM’s, such as Django and SQLAlchemy, because it leads to your application making more database queries than necessary. Let’s look at a basic example in Django. class Artist(models.Model): name = models.CharField(max_length=255) class Song(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=255) def print_songs(): for song in Song.objects.all(): print(f"{song.artist.name} - {song.name}") Now let’s create a unit test to ensure print_songs runs successfully....

April 13, 2021 · 3 min · Johnny Metz