为什么在将 __init__(self) 方法添加到 Django rest 框架视图集 class 时出现错误?

Why I get an error when adding __init__(self) method to Django rest framework viewset class?

我在尝试构建 Django 时总是遇到错误 API。

我有这个class:

from uuid import UUID
from django.shortcuts import render
from django.http.response import JsonResponse
from django.http.request import HttpRequest
from rest_framework import viewsets, status
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from Instruments import serializers
from Instruments.services import InstrumentsService
from rest_framework.decorators import api_view
from Instruments.services import InstrumentsService
from Instruments.models import Instrument
from Instruments.serializers import InstrumentsSerializer


# Application views live here
class InstrumentViewSet(viewsets.ViewSet):
    # instruments = Instrument.objects.all()

    def __init__(self):
        # self.instrument_service = InstrumentsService()
        # self.instruments = Instrument.objects.all()
        super().__init__()

    def list(self, request: HttpRequest):

        try:
            self.instruments = Instrument.objects.all()
            serializer = InstrumentsSerializer(self.instruments, many=True)
            # data = self.instrument_service.get_instruments()
            data = serializer.data
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_400_BAD_REQUEST,
                safe=False,
            )

init() 方法正在定义时,即使它只是在做 pass 当我发送请求时,django 服务器给我这个错误:

TypeError at /api/
__init__() got an unexpected keyword argument 'suffix'

如果我删除或注释掉 init() 方法 works.why??

“得到一个意外的关键字参数”异常是相当具有描述性的。这意味着您的 class 实例(在本例中为您的 ViewSet 实例)是使用您未处理的关键字参数初始化的。这可以通过在 init 方法中执行以下操作来解决:

def __init__(self, **kwargs):
    # self.instrument_service = InstrumentsService()
    # self.instruments = Instrument.objects.all()
    super().__init__(**kwargs)

这是必需的,因为超级 class(视图)在初始化实例时使用 **kwargs。

郑重声明,这并没有按预期使用 Django。 Django 从来就不是为服务层设计的,像这样使用 init 方法会适得其反,因为 ViewSet 需要一个查询集变量。我鼓励您在继续您的这个项目之前更彻底地阅读文档。