我正在创建一个restapi视图,该视图应该是所有对象的一个端点。但是无论我做什么,它始终执行post方法。终端向我展示了例如patch方法已经执行,但始终执行确实发布并因此创建了一个新对象,并且它也没有删除该对象,它向我显示了正确的状态代码,但是该对象仍然存在。
这是我的观点
class StatusGET_New(
generics.ListCreateAPIView,
mixins.RetrieveModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin
):
queryset = Status.objects.all()
serializer_class = StatusSerializers
permission_classes = []
def perform_destroy(self, instance):
if instance is not None:
return instance.delete()
return None
def get_queryset(self):
qs = Status.objects.all()
query = self.request.GET.get('q')
if query is not None:
qs = qs.filter(
content__icontains = query
)
return qs
def get_object(self):
request = self.request
passed_id = request.GET.get('pk',None)
queryset = self.get_queryset()
obj = None
if passed_id is not None:
obj = get_object_or_404(queryset,pk = passed_id)
self.check_object_permissions(request,obj)
return obj
def get(self,request,*args,**kwargs):
passed_id = self.request.GET.get('pk',None)
if passed_id is not None:
return self.retrieve(request,*args,**kwargs)
return super().get(request,*args,**kwargs)
def post(self,request,*args,**kwargs):
return self.create(request,*args,**kwargs)
def put(self,request,*args,**kwargs):
url_passed_id = request.GET.get("pk",None)
json_data = {}
body_ = request.body
if is_json(body_):
json_data = json.loads(request.body)
new_passed_id = json_data.get('pk',None)
passed_id = url_passed_id or new_passed_id or None
self.passed_id = passed_id
return self.update(request,*args,**kwargs)
def patch(self,request,*args,**kwargs):
url_passed_id = request.GET.get("pk",None)
json_data = {}
body_ = request.body
if is_json(body_):
json_data = json.loads(request.body)
new_passed_id = json_data.get('pk',None)
passed_id = url_passed_id or new_passed_id or None
self.passed_id = passed_id
return self.partial_update(body_,*args,**kwargs)
def delete(self,request,*args,**kwargs):
url_passed_id = request.GET.get("pk",None)
json_data = {}
body_ = request.body
if is_json(body_):
json_data = json.loads(request.body)
new_passed_id = json_data.get('pk',None)
passed_id = url_passed_id or new_passed_id or None
self.passed_id = passed_id
return self.destroy(request,*args,**kwargs)
答案 0 :(得分:0)
您正在混合ListCreateAPIView和mixins。相反,您应该将GenericAPIView与mixins一起使用,通常,mixins应该在继承顺序中排在GenericAPIView之前。
class StatusGET_New(
generics.GenericAPIView,
mixins.RetrieveModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin):
...
但是从您的代码来看,您似乎想同时在同一视图中处理明细路径和列表路径,因此您需要的是视图集。所以应该像这样:
from restframework.viewsets import ModelViewSet
class StatusGET_New(ModelViewSet):
...
模型视图集已经具有所有这些方法的实现,因此您可能需要检查代码并在可能的情况下使用默认实现。
正如评论一样,您确实可以改善视图命名-类似于StatusView
或StatusViewSet