[Answered ]-How to cache SerializerMethodField result

1👍

Well, first of all, I should say that what you have implemented in this piece of code below:

    ...
    @cached_property
    def item_product_description(self):
        return self.product.product_description

And using @cached_property alone doesn’t cache the data for you, you just created a property in the model for get_product_description serializer method, And this does not reduce the volume and number of your queries to the database at all; Of course you need .bind() method in your serializer method like below:

class BlobSerializer(SerializerCacheMixin, serializers.Serializer):
   blobs = serializers.SerializerMethodField()

   def get_blobs(self, instance):
       # recursive serializer
       serializer = self.__class__(instance.results, many=True)
       serializer.bind('*', self)
       return serializer.data

But in order to cache the result of this method As you asked in your question there is a good project in Pypi called drf-serializer-cache you can use it easily for this purpose, for example, the following piece of code is taken from the document of this project:

from drf_serializer_cache import SerializerCacheMixin
from rest_framework import serializer

class ResultSerializer(SerializerCacheMixin, serializers.Serializer):
   results = serializers.SerializerMethodField()

   def get_results(self, instance):
       # recursive serializer
       serializer = self.__class__(instance.results, many=True)
       serializer.bind('*', self)  # bind call is essential for >efficient cache!
       return serializer.data

Also if you want to implement it yourself in your project Seeing the implementation of SerializerCacheMixin object in this project can help you a lot or even use it directly.

👤Javad

0👍

You can leverage Django's cache framework to cache the result of a SerializerMethodField. It would look something like this:
from django.core.cache import cache

class MySerializer(serializers.Serializer):
    my_field = serializers.SerializerMethodField()

    def get_my_field(self, obj):
        # Get cached value
        value = cache.get("my_field_%s" % obj.pk)
        if value is None:
            # Value is not cached, compute it
            value = ...
            # Cache the value
            cache.set("my_field_%s" % obj.pk, value, 3600)
        return value

This will cache the result of the field for 1 hour (3600 seconds), using a cache key that depends on the object's primary key.
You can of course adapt the caching logic to your exact use case.

Leave a comment