Wrap DRF serializer constructor

Let's say I have the following Django REST Framework serializer:

class MySerializer(serializer.ModelSerializer):
    items = serializers.SerializerMethodField()
    users = UserSerializer(many=True)

    class Meta:
        model = MyModel
        fields = ("id", "items", "users")

I want to wrap the serializer constructor in queries_disabled from django-zen-queries to ensure all data has been prefetched and there are no N+1 violations.

How can I do this?

There are few serialization workflows that may execute unnecessary queries, so it is required to decorate a few methods:

  • is_valid as validation process entry point (to_internal also called inside).
  • to_internal as entry point for conversion from represenation (writing data).
  • to_representation as entry point for conversion from internal (reading data).

Also there is a save() (calls create(), update()) method, but I think you don't want to disable queries here.

The shortest example:

from django.utils.decorators import method_decorator


@method_decorator(queries_disabled(), name='is_valid')
@method_decorator(queries_disabled(), name='to_internal')
@method_decorator(queries_disabled(), name='to_representation')
class MySerializer(serializer.ModelSerializer):
    items = serializers.SerializerMethodField()
    users = UserSerializer(many=True)

    class Meta:
        model = MyModel
        fields = ("id", "items", "users")
Back to Top