django-rest-framework和返回字典

时间:2013-09-12 09:03:19

标签: django-rest-framework

我正在寻找一个灵魂来接收json响应就像{}中的字典而没有额外的[]。请仔细阅读下面的代码。

在views.py中的

我有:

class authTest(ListAPIView):
    permission_classes = (IsApiUser,)
    serializer_class = authDistinctSerializer

    def get_queryset(self):
        if not self.request.user:
            raise exceptions.AuthenticationFailed

        user = self.request.user
        authz = authDistinctSqlView.objects.filter(emailId=user)

        return authz

接下来在serializers.py中我有:

class authSerializer(serializers.ModelSerializer):
    class Meta:
        model = authSqlView
        fields = ('countryName', 'courrencyCode', 'countryCode',)


class authDistinctSerializer(serializers.ModelSerializer):
    countries = authSerializer(many=True)
    status = serializers.CharField(source='show_auth_status')

    class Meta:
        model = authDistinctSqlView
        fields = ('status', 'emailId', 'region', 'url', 'countries',)

我在[]中收到以下结果 我应该做什么来获得相同的结果只是dict {}没有额外的顶部[]?

[

{
    "status": "Authorized",
    "emailId": "user@domain.com",
    "region": "EMEA",
    "url": "127.0.0.1",
    "countries": [
        {
            "countryName": "POLAND",
            "courrencyCode": "PLN",
            "countryCode": "PL"
        }
    ]
}

]

1 个答案:

答案 0 :(得分:1)

您可能已经猜到,您的结果将作为列表返回,因为您使用的是ListAPIView

使用RetrieveAPIView您需要将get_queryset替换为get_object

def get_object(self):
    # Don't need these two lines if you have implemented authentication properly:
    # if not self.request.user:
    #    raise exceptions.AuthenticationFailed

    user = self.request.user
    authz = authDistinctSqlView.objects.get(emailId=user.email)

    return authz

无论您是否尝试从URL中提取任何值,它都应该有效。