DRF-SerializerMethodField

时间:2019-07-01 06:25:21

标签: django django-rest-framework

我具有如下API视图:-

class ProfileAPI(generics.RetrieveAPIView):
    serializer_class = ProfileSerializer

    def get_object(self):
        try:
            return Profile.objects.get(user=self.request.user)
        except:
            return None
            # I don't raise NotFound here for a reason.
            # I don't want a 404 response here, but a custom HTML response, explained below.



class ProfileSerializer(serializers.ModelSerializer):

    html = serializers.SerializerMethodField()

    def get_html(self, obj):
        # some custom HTML response based on whether the user obj is `None` or not.
        if not obj:
            return NOT_LOGGED_IN_HTML

        return CUSTOM_HTML

    class Meta(object):
        model = Profile
        fields = ('html',)

现在,当用户登录时,我在响应中得到了html键。但是,当用户为“无”(注销)时,我得到一个空响应。为什么?以及我该如何纠正?

1 个答案:

答案 0 :(得分:1)

据我从retrievedata方法的实现中了解,您需要传递Profile的实例来填充数据。我会这样处理:

class ProfileAPI(generics.RetrieveAPIView):
    serializer_class = ProfileSerializer

    def get_object(self):
        try:
            return Profile.objects.get(user=self.request.user)
        except:
            return Profile()  # empty object instance


class ProfileSerializer(serializers.ModelSerializer):

    html = serializers.SerializerMethodField()

    def get_html(self, obj):
        if obj and obj.pk:
            return CUSTOM_HTML
        return NOT_LOGGED_IN_HTML       

    class Meta(object):
        model = Profile
        fields = ('html',)