“ReturnList”对象在Django restframework中没有属性“get”

2024-10-03 02:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在DRF中创建自定义渲染方法,以下是我的代码:

序列化程序

class SupplierSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Supplier
        fields = [
            # "plan",
            "type",
            "created",
            "id",
            "name",
            "bio",
            "established",
            "logo",
            "last_updated",
            "is_active",
            "date_to_pay",
            "mobile",
            "password",
        ]

渲染器

class ApiRenderer(BaseRenderer):

    media_type = 'text/plain'
    format = 'txt'

    def render(self, data, accepted_media_type=None, renderer_context=None):
        response_dict = {
            'status': 'failure',
            'data': {},
            'message': '',
        }
        if data.get('data'):
            response_dict['data'] = data.get('data')
        if data.get('status'):
            response_dict['status'] = data.get('status')
        if data.get('message'):
            response_dict['message'] = data.get('message')
        data = response_dict
        return json.dumps(data)

设置

RENDERER_CLASSES = (
    'market_control_panel.renderers.ApiRenderer',
)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',  # <-- And here
        'rest_framework.authentication.TokenAuthentication',  # <-- And here
    ],
    # testing ftp upload after comment
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_RENDERER_CLASSES': RENDERER_CLASSES,

}

但当我尝试打开任何API链接时,会出现以下错误:

'ReturnList' object has no attribute 'get'

Tags: restdefaultmessagedatagetifresponsetype
1条回答
网友
1楼 · 发布于 2024-10-03 02:31:50

render(...)方法的data参数可以是任何东西,例如,listdictstring{}等。这个data由视图(函数或类)返回,您应该期望它是任何东西

在您的情况下,视图可能返回类似列表的响应(假设您访问了列表视图),因此返回的对象不支持.get()方法,因此出现错误

<>我不确定你在做什么,但是,你应该在更新渲染逻辑时考虑这一点。

相关问题 更多 >