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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With