【发布时间】:2020-04-16 07:52:21
【问题描述】:
出于某种奇怪的原因,我收到了AttributeError: 'QuerySet' object has no attribute 'description'。我的模型很简单:
class Question(models.Model):
PROFILE = 0
EVENT_REPORT = 1
UNIVERSITY_REPORT = 2
USER_REPORT = 3
TYPE_LIST = [PROFILE, EVENT_REPORT, UNIVERSITY_REPORT, USER_REPORT]
TYPE_CHOICES = (
(PROFILE, 'Profile'),
(EVENT_REPORT, 'User Report'),
(UNIVERSITY_REPORT, 'University Report'),
(USER_REPORT, 'User Report'),
)
description = models.CharField(max_length=100)
type =models.IntegerField(choices=TYPE_CHOICES, default=PROFILE)
def __str__(self):
return self.description
序列化器:
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields = '__all__'
查看:
class QuestionListView(ListAPIView):
authentication_classes = (JWTTokenUserAuthentication, TokenAuthentication)
serializer_class = QuestionSerializer
permission_classes = (IsAuthenticated, )
def get(self, request, *args, **kwargs):
"""
takes type paramter. type must be an interger. Types are {}.
Returns list of all questions of that type.
""".format(Question.TYPE_CHOICES)
types = Question.TYPE_LIST
try:
question_type = kwargs['question_type']
question_type = int(question_type)
if question_type not in types:
raise Exception("type must be in {}".format(Question.TYPE_CHOICES))
questions = Question.objects.filter(type=question_type)
serializer = QuestionSerializer(questions)
return Response(serializer.data)
except ValueError:
raise ValidationError('Must be an interger.')
except Exception as e:
raise e
raise ValidationError(e)
知道我可能错过了什么吗? 我已经创建了对象,它们在管理视图中看起来很好,但是当我请求按类型列出问题时,我得到了错误。
AttributeError: Got AttributeError when attempting to get a value for field `description` on serializer `QuestionSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'description'.
【问题讨论】:
-
也许你应该进行迁移?
标签: django django-rest-framework django-views django-admin