How to create a drop in serializer replacement for Django ReadOnlyViewSet that is very fast?

I've noticed that Django Serializers are extremely slow even after N+1 type problems (I think). I'm basing that off my own experience and questions such as these

In my case I have a model for users

from django.contrib.auth.models
from rest_framework.viewsets import ReadOnlyModelViewSet

class UserViewSet(ReadOnlyModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filterset_fields = {'groups__name': ['exact', 'in']

If I have a function like:

def serialize_user(user_instance):
    return {f: getattr(user_instance, f) for f in user_instance._meta.fields}

how do I write a custom serializer class so I can use it as serializer_class = MyUserSerializer and it skips validation etc. I expect since it's readonly validation also doesn't make as much sense but maybe I'm missing something.

Вернуться на верх