1

我正在寻找一个灵魂来接收 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 {} 而没有额外的 top [] ?

[

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

]
4

2 回答 2

1

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

使用 aRetrieveAPIView您需要将您的替换get_querysetget_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 中提取任何值,它都应该可以工作。

于 2013-09-12T12:48:33.713 回答
0

使用get而不是filter获取字典格式的单个数据响应

authz = authDistinctSqlView.objects.get(emailId=user) #get instead of filter
于 2021-09-28T09:56:30.687 回答