Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file params (size, filename) in django rest framewrok

I need to get file params in my rest api.

Model:

class Movie(models.Model):
    title = models.CharField(max_length=100)
    attachment = models.FileField(upload_to='files/courses/', default=None, blank=True, null=True)

    def __str__(self):
        return self.title

Serializer:

class MovieSerializer(serializers.ModelSerializer):
    attachment = serializers.FileField()

    class Meta:
        model = Movie
        fields = ('title','attachment')

View:

class MovieViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer

When I do GET request, I get the title, and file url, But I wnat to get also file size, and file name. How to do that?

like image 845
yestema Avatar asked Apr 09 '19 14:04

yestema


1 Answers

One of the simple solutions is overriding the to_representation() method of the MovieSerializer class as,

class MovieSerializer(serializers.ModelSerializer):
    attachment = serializers.FileField()

    class Meta:
        model = Movie
        fields = ('title', 'attachment')

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        attachment = {
            "url": representation.pop("attachment"),
            "size": instance.attachment.size,
            "name": instance.attachment.name,
        }
        representation['attachment'] = attachment
        return representation
like image 64
JPG Avatar answered Oct 08 '22 07:10

JPG