django-rest-framwork:AttributeError,'Response'对象没有属性'title'



AttributeError:尝试获取序列化程序QuestionSerializer上字段title的值时出现AttributeError。序列化程序字段的名称可能不正确,并且与Response实例上的任何属性或键都不匹配。原始异常文本为:"Response"对象没有属性"title"。

型号.py

class Question(models.Model):
title = models.TextField(null=False,blank=False)
status = models.CharField(default='inactive',max_length=10)
created_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL)
def __str__(self):
return self.title
class Meta:
ordering = ('id',)

urls.py

urlpatterns = [
path('poll/<int:id>/', PollDetailsAPIView.as_view()),
]

序列化程序.py

class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields =[
'id',
'title',
'status',
'created_by'
]

视图.py

class PollDetailsAPIView(APIView):

def get_object(self, id):
try:
return Question.objects.get(id=id)
except Question.DoesNotExist:
return Response({"error": "Question does not exist"}, status=status.HTTP_404_NOT_FOUND)

def get(self, request, id):
question = self.get_object(id)
serializer = QuestionSerializer(question)
return Response(serializer.data)

在poster上,我试图获得一个不存在的id,但我没有得到这个响应"error": "Question does not exist"Error: 404,而是一直得到error 500 Internal server error

当您试图获取不存在的对象时,get_object方法返回一个Response,然后将其传递给序列化程序。由于它无法序列化Response,因此它将引发一个AttributeError。您应该做的是在except:中引发Http404错误

def get_object(self, id):
try:
return Question.objects.get(id=id)
except Question.DoesNotExist:
raise Http404('Not found')

或使用django快捷方式get_object_or_404:

from django.shortcuts import get_object_or_404

class PollDetailsAPIView(APIView):
def get(self, request, id):
question = get_object_or_404(Question, id=id)
serializer = QuestionSerializer(question)
return Response(serializer.data)