编写Get函数会给我一个属性错误

时间:2019-02-13 05:29:15

标签: python django

这是我的模特。py

class Grade(models.Model):
    grade = models.CharField(max_length=255, primary_key=True)

这是我执行get的视图(不需要发布,如果也需要发布,则可以运行)。

class GetGrade(generics. GenericAPIView):
    '''
    GET check/
    '''
    queryset = Grade.objects.all()
    serializer_class = DataSerializer


    def get(self, request, *args, **kwargs):
        a_grade = Grade.objects.all()
        return Response(
            data=DataSerializer(a_grade).data,
            status=status.HTTP_200
        )

我的序列化器如下:

class DataSerializer(serializers.ModelSerializer):
    class Meta:
        model = Grade
        fields = ("grade",)

一切似乎都很简单。我可能正在做一些愚蠢的事情。

AttributeError at /check/
Got AttributeError when attempting to get a value for field `grade` on serializer `DataSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.

原始例外文本为:

'QuerySet' object has no attribute 'grade'.
    Request Method: GET
    Request URL:    http://127.0.0.1:8000/check/
    Django Version: 2.1.5
    Exception Type: AttributeError
    Exception Value:    Got AttributeError when attempting to get a value for field `grade` on serializer `DataSerializer`.
    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 'grade'.

2 个答案:

答案 0 :(得分:1)

这样吧:

class GetGrade(generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        a_grade = Grade.objects.all()
        return Response(
            data=DataSerializer(a_grade, many=True).data,  # passed many=True as known argument
            status=status.HTTP_200
        )

发生错误是因为您通过DataSerializer传递了Queryset。当您调用data的{​​{1}}方法时,它试图从Queryset获取值DataSerializer属性。因此,您需要传递grade,以便序列化程序知道您正在传递queryset或对象列表。如果希望序列化程序处理单个对象,则可以这样做:

many=True

最后,一种更清洁的方法是使用ListModelMixin。例如:

class GetGrade(generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        a_grade = Grade.objects.all().first()  # it will return first object of queryset
        return Response(
            data=DataSerializer(a_grade).data, 
            status=status.HTTP_200
        )

答案 1 :(得分:0)

在您的 Serailizers.py 中,您需要使用 model 方法从API中的模型中获取对象:

class GetGrade(generics. GenericAPIView):
    '''
    GET check/
    '''
    model = Grade   # <---Add This in place queryset
    serializer_class = DataSerializer