Django Rest 框架不正确的模型视图响应



我对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',
        ]                

使用这个:

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)
你可以

这样做,

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

最新更新