[Django]-ModelSerializer is extremely slow in Django REST framework

15đź‘Ť

Almost always the performance issues come from N+1 queries. This is usually because you are referencing related models, and a single query per relationship per object is generated to get the information. You can improve this by using .select_related and .prefetch_related in your get_queryset method, as described in my other Stack Overflow answer.

The same tips that Django provides on database optimization also applies to Django REST framework, so I would recommend looking into those as well.

The reason why you are seeing the performance issues during serialization is because that is when Django makes the queries to the database.

13đź‘Ť

ModelSerializers are slow, you said it yourself. Here’s some more information on why it happens and how to speed things up: https://hakibenita.com/django-rest-framework-slow

  • In performance critical endpoints, use a "regular" serializer, or none at all.
  • Serializer fields that are not used for writing or validation, should be read only.
👤barrtin

8đź‘Ť

I know this is old and you probably solved your problem already … but for anyone else making it to this article…

The problem is you’re doing a blind

select_related()

with no parameters, which does absolutely nothing for your query. What you really need to do is

prefetch_related('user_profile')

Without getting into the details, select_related is for “to one” relationships, and prefetch_related is for “to many” relationships. In your case, you’re using a reverse relationship which is a “to many” query.

Your other problem is that you weren’t using the reverse relationship correctly. change your get_queryset() in your serializer to this and I think you’ll have what you want:

def get_queryset(self):
    return UserProfile.objects.prefetch_related('user_profile').all()
👤jaredn3

Leave a comment