在django rest framewrok

时间:2019-04-09 14:52:05

标签: django django-rest-framework

我需要在我的REST API中获取文件参数

型号:

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

序列化器:

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

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

查看:

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

当我执行GET请求时,我得到了标题和文件url, 但是我要获得文件大小和文件名。 该怎么做?

1 个答案:

答案 0 :(得分:2)

一种简单的解决方案是将 to_representation() 类的 MovieSerializer 方法重写为

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