Django REST框架和FileField绝对url [英] Django REST Framework and FileField absolute url

查看:1857
本文介绍了Django REST框架和FileField绝对url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个简单的Django应用程序,其中包含以下模型:

I've defined a simple Django app that includes the following model:

class Project(models.Model):
    name = models.CharField(max_length=200)
    thumbnail = models.FileField(upload_to='media', null=True)

(技术上是的,那可能是一个ImageField。)

(Technically yes, that could have been an ImageField.)

在模板中,包含MEDIA_URL值(在settings.py中正确编码)作为缩略图URL的前缀。以下工作正常:

In a template, it's easy enough to include the MEDIA_URL value (duly coded in settings.py) as a prefix to the thumbnail URL. The following works fine:

<div id="thumbnail"><img src="{{ MEDIA_URL }}{{ current_project.thumbnail }}" alt="thumbnail" width="400" height="300" border="0" /></div>

使用DRF,我已经定义了一个名为ProjectSerializer的超链接模型串行器后代:

Using DRF, I've defined a HyperlinkedModelSerializer descendant called ProjectSerializer:

class ProjectSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Project
        fields = ( 'id' ,'url', 'name', 'thumbnail')

非常简单的ModelViewSet后代:

And I've defined a very straightforward ModelViewSet descendant:

class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

生成的JSON样本如下所示:

A sample of the resulting JSON looks like this:

{
    "id": 1, 
    "url": "http://localhost:8000/api/v1/projects/1/", 
    "name": "Institutional", 
    "thumbnail": "media/institutional_thumb_1.jpg"
}

我还没有能够弄清楚如何提供缩略图这个字段在我的项目的JSON表示中包含了图像的完整URL。

I have not yet been able to figure out how to provide a thumbnail field that includes the full url to the image in my project's JSON representation.

我会认为我需要在ProjectSerializer中创建一个自定义字段,但是还没有

I would think that I would need to create a custom field in the ProjectSerializer, but have not been successful.

推荐答案

尝试 SerializerMethodField

示例(未测试):

class MySerializer(serializers.ModelSerializer):
    thumbnail_url = serializers.SerializerMethodField('get_thumbnail_url')

    def get_thumbnail_url(self, obj):
        return self.context['request'].build_absolute_uri(obj.thumbnail_url)

请求必须可用于序列化程序,因此可以为您构建完整的绝对URL。一种方法是在创建序列化程序时明确传递它,类似于:

The request must available to the serializer, so it can build the full absolute URL for you. One way is to explicitly pass it in when the serializer is created, similar to this:

serializer = MySerializer(account, context={'request': request})

这篇关于Django REST框架和FileField绝对url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆