【问题标题】:Django DRF Field Exists but Serializer does not recognize itDjango DRF 字段存在但序列化程序无法识别它
【发布时间】: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


【解决方案1】:

由于您正在序列化 QuerySet 对象,因此您应该传递 many=True

questions = Question.objects.filter(type=question_type)
serializer = QuestionSerializer(questions, many=true)

【讨论】:

    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2020-05-27
    • 2017-05-24
    • 2014-08-05
    相关资源
    最近更新 更多