TAGS :Viewed: 11 - Published at: a few seconds ago

[ Django Model Method Performance With self.image.width ]

I have the following Model method....

def make_image_width(self):
    """
    Returns image width of the object.
    """
    if self.image:
        return self.image.width
    return "null"

When I run this within a serializers it take 2 mins to render 100 objects.

class ImageSerializer(serializers.HyperlinkedModelSerializer):
    image_width = serializers.ReadOnlyField(source='make_image_width')


    class Meta:
        model = Image
        fields = (
            'id','image_width',)

Why is self.image.width so slow? and how can I improve this?

Answer 1


Your method reads image file to get the width.

You should create an integer field in your model and point to it by using width_field attribute of the ImageField.