Django REST 框架 405 错误

Django REST framework 405 Error

我有一个这样编码的序列化程序:

class InternationalSerializer(serializers.Serializer):
    """ Serializer for International
        Serializes version, which is displayed on the
        International page
    """

    overall_version = serializers.SerializerMethodField('get_overall_version',
                        read_only=True)

    def get_overall_version(self):
         # sum up all the individual country versions 
         #  to keep a unique value of the overall 
         # International version
         sum_of_versions = 0
         for key in constants.country_versions:
             sum_of_versions+=key.value()

     return sum_of_versions

~

现在,我希望通过 views.py 文件显示 InternationalSerializer class 的 'overall_version'。这是我的代码:

class International(generics.GenericAPIView):

    serializer_class = InternationalSerializer()

每当我尝试加载 /domain/international/ 时,我都会收到 405 Method not allowed 错误。 这是我的 urls.py 包含的内容:

urlpatterns = patterns('',
    url(r'^international/$', views.International.as_view()), ...

这可能是什么问题? 谢谢!

在你的情况下你似乎并不需要序列化器,因为你不对任何对象进行操作(无论是 python 还是 django 模型对象)

因此,您可以 return 直接响应,而不是使用序列化程序:

from rest_framework import generics
from rest_framework.response import Response

class International(generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        sum_of_versions = 0
        for key in constants.country_versions:
            sum_of_versions+=key.value()

        return Response({'sum_of_versions': sum_of_versions})

您得到 405 的原因是您没有在通用 api 视图 class.

上指定 get 方法