django get file size and put it in serializer

Viewed 295

serializers.py

class ModFileSerializer(serializers.ModelSerializer):
    size = serializers.CharField(default=os.path.getsize('file'), max_length=16)
    class Meta:
        model = models.ModFile
        fields = '__all__'

        read_only_fields = (
        'size',
        )

models.py

class ModFile(models.Model):
    downloads = models.IntegerField(default=0)
    file = models.FileField(upload_to='mods/')
    created_at = models.DateTimeField(auto_now_add=True)

Here I have a serializer for the ModFile model and the only thing that's missing is the file's size, I know os.path.getsize() needs the exact location of the file so how do I actually access the file field from the model in order to pass in the getsize() function or is there a better way to do it?

2 Answers
class ModFileSerializer(serializers.ModelSerializer):
    size = serializers.SerializerMethodField()

    def get_size(self, obj):
        return os.path.getsize(obj.file.path)
        
    class Meta:
        model = models.ModFile
        fields = '__all__'

        read_only_fields = (
            'size',
        )

I think this would work any time you use this serializer.

obj in the get_size method is the instance itself.

Add a to_representation method to your serializer which is much easy.

class ModFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.ModFile
        fields = '__all__'

    def to_representation(self, instance):
        rep = super(ModFileSerializer, self).to_representation(instance)
        rep['size'] = instance.file.size
        return rep
Related