问题描述
AttributeError::尝试在序列化器 QuestionSerializer
上获取字段 title
的值时,出现AttributeError.序列化程序字段的名称可能不正确,并且与 Response
实例上的任何属性或键都不匹配.原始异常文本为:响应"对象没有属性标题".
AttributeError: Got AttributeError when attempting to get a value for field title
on serializer QuestionSerializer
.The serializer field might be named incorrectly and not match any attribute or key on the Response
instance.Original exception text was: 'Response' object has no attribute 'title'.
models.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()),
]
serializers.py
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields =[
'id',
'title',
'status',
'created_by'
]
views.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)
关于邮递员,我试图获取一个不存在的id,而不是得到此响应"error":问题不存在"
和一个 Error:404
,我不断收到错误500内部服务器错误
.
on postman, i am trying to get an id that doesnt exist but instead of getting this response "error": "Question does not exist"
and an Error: 404
, i keep getting error 500 Internal server error
.
推荐答案
当您尝试获取不存在的对象时,您的 get_object
方法将返回 Response
然后传递给序列化器.由于无法序列化 Response
,因此会引发 AttributeError
.您应该做的是在 except
之外的 Http404
中引发错误:
When you are trying to get non existing object, your get_object
method returns a Response
, which is then passed to the serializer. Since it cannot serialize Response
, it raises an AttributeError
. What you should do is either raising an Http404
error in except
:
def get_object(self, id):
try:
return Question.objects.get(id=id)
except Question.DoesNotExist:
raise Http404('Not found')
或使用Django快捷方式 get_object_or_404
:
or use django shortcut 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)
这篇关于django-rest-framwork:AttributeError,“响应"对象没有属性“标题"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!