Django: Optimize Database Searches

Asked

Viewed 54 times

0

I am doubtful in the following exercise: The route /Albums/ is returning a listing of the albums with the artists of the album, but in some of our clients that use databases stored on own servers it is very slow. When accompanying SQL queries with a profiler has been detected that many queries are being held at the bank and this is causing the slowness

that’s what’s represented in the view:

class AlbumListAPIView(ListAPIView):
    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

there is some way to optimize this queryset ?

  • Lucas, I would need more information on how this model Album works to see if you have many relationships, but I would recommend taking a look at the select_related method of Django - https://docs.djangoproject.com/pt-br/3.2/ref/models/querysets/#select-Related

2 answers

0

Talk to me, Dev. I believe I have already found a good solution to your question, but I realized that it had not been directly answered and decided to share an article that has already helped me.

Possibly, your Album model should have a relationship with the Artist model. It is likely to be a Manytomany relationship:

class Album(models.Model):
    artistas = models.ManyToManyField(Artista)

If this is the case, I will point out a solution to decrease your queries to the bank.

class AlbumListAPIView(ListAPIView):
    queryset = Album.objects.prefetch_related('artistas').all()
    serializer_class = AlbumSerializer

Regardless of the number of albums or artists your bank has, only 02(two) queries will be performed by Python. One to pick up the albums and one to pick up the artists. However, using filters in Querysets can help in useful data traffic.

The article, which helped me in the past is still on the air: http://pythonclub.com.br/django-introducao-queries.html A more recent article on optimization: https://betterprogramming.pub/django-select-related-and-prefetch-related-f23043fd635d

-1

To Queryset is an SQL query, so you have to go filtering the data you don’t need.

Ex: In a table you may have deleted or inactivated albums that you don’t need to show. So instead of making a Album.objects.all(), can be Album.objects.filter(is_delete=False) or Album.objects.filter(is_ativo=True). This is just an example, but can optimize the search to make it lighter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.