【问题标题】:Djangorestframework returns: TypeError: get_extra_actions() missing 1 required positional argument: 'self' when declaring get()Djangorestframework返回:TypeError:get_extra_actions()缺少1个必需的位置参数:声明get()时'self'
【发布时间】:2021-09-20 14:28:12
【问题描述】:

我对我的代码有点困惑:

from django.db.models import query
from django.shortcuts import render
from rest_framework.views import APIView
from .models import Publication
from rest_framework.response import Response
from .serializer import PublicationSerializer

# Create your views here.

class PublicationView(APIView):
    
    serial_class = PublicationSerializer()

    def get_extra_actions(self):
        return [ self.get() ]

    def get(self, request):
        detail = [ {'pub_id': i.pub_id, 'pub_date': i.pub_date, 'title': i.title, 'description': i.description, 'link': i.link} for i in Publication.objects.all() ]
        return Response(detail)

但我仍然收到上述错误的返回。有什么想法或帮助吗?告诉我!

【问题讨论】:

  • 我认为这是因为在 get_extra_actions 在 return 语句中调用 self.get() 时缺少请求参数
  • 不幸的是,我没有那么简单:(当我这样做时,它也说get_extra_actions(self) missing 1 required positional argument: 'self'

标签: python django django-models django-rest-framework django-views


【解决方案1】:

在做了一些研究之后,我发现使用 APIview 并不是我真正需要的。使用viewsets.ModelViewSet 要简单得多,只需两行代码。

class PublicationView(viewsets.ModelViewSet):
   serializer_class = PublicationSerializer
   queryset = Publication.objects.all()

将 api 路由回urls.py 后,一切正常!

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2023-02-06
    • 1970-01-01
    • 2021-09-15
    • 2013-07-06
    • 2022-01-05
    • 2017-03-28
    • 2020-01-07
    相关资源
    最近更新 更多