I created the following serializer where I call the function _calculate_image_dimensions twice. I now tried @cachedproperty but doesn't work because I have to pass the values width, height. However, they will not change for get_width and get_height. Is there a way to make sure the calculation only computes once?
class IntegrationImageSerializer(serializers.ModelSerializer):
width = serializers.SerializerMethodField()
height = serializers.SerializerMethodField()
class Meta:
model = IntegrationImage
fields = ("image", "width", "height")
def _calculate_image_dimensions(self, width, height) -> int:
MAX_IMAGE_SIZE = 350
aspect_ratio = width / height
if width > height:
width = MAX_IMAGE_SIZE
height = width / aspect_ratio
else:
height = MAX_IMAGE_SIZE
width = height * aspect_ratio
return round(width), round(height)
def get_width(self, obj: IntegrationImage) -> int:
width, height = self._calculate_image_dimensions(
obj.image.width, obj.image.height
)
return width
def get_height(self, obj: IntegrationImage) -> int:
width, height = self._calculate_image_dimensions(
obj.image.width, obj.image.height
)
return height