Django Rest框架错误的模型视图响应

时间:2017-05-16 03:02:48

标签: python django django-rest-framework

我对drf有一些问题,有人可以指出我做错了什么吗?

这是我的视图功能,我也实现了easy_thumbnails,这样我就可以裁剪图像,如果有这样的请求。

from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from .models import Image
from .serializers import ImageSerializer
from easy_thumbnails.files import get_thumbnailer

class ImageViewSet(viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer

    def retrieve(self, request, pk=None):
        height = request.GET.get('height', None)
        width = request.GET.get('width', None)
        print("height = {}".format(height))
        print("width = {}".format(width))
        print("id = {}".format(pk))
        img = Image.objects.get(pk = pk)
        if height and width:
            options = {'size': (height, width), 'crop': True}
            thumb_url = get_thumbnailer(img.image).get_thumbnail(options).url
        else:
            thumb_url = get_thumbnailer(img.image).url
        return Response(thumb_url)

现在如果转到http://127.0.0.1:8000/api/images/它会返回一个图像列表

http://127.0.0.1:8000/api/images/1/?height=320&width=420会返回类似

的回复
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

"/media/10438039923_2ef6f68348_c.jpg.320x420_q85_crop.jpg" 

我想要一个像字段名这样的回复。

{
    "title": "Item 1",
    "description": "Description 1",
    "image": "http://127.0.0.1:8000/media/10438039923_2ef6f68348_c.jpg"
}

我该如何解决这个问题?我是drf和django的新手

这是我的序列化程序类

from rest_framework import serializers
from .models import Image

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = [
            'title',
            'description',
            'image',
        ]                

2 个答案:

答案 0 :(得分:2)

使用它:

def retrieve(self, request, pk=None):
    height = request.query_params.get('height', None)
    width = request.query_params.get('width', None)
    img = self.get_object()
    if height and width:
        options = {'size': (height, width), 'crop': True}
        thumb_url = get_thumbnailer(img.image).get_thumbnail(options).url
    else:
        thumb_url = get_thumbnailer(img.image).url
    serializer = self.get_serializer(img)
    # insert thumb_url into data if you need it
    response_dict = {}
    response_dict.update(serializer.data)
    response_dict['image'] = thumb_url
    return Response(response_dict)

答案 1 :(得分:0)

你可以这样做,

return Response({"title": img.title, "description": img.description,
                 "image": img.image, "thumbnail": thumb_url})