首页 > 解决方案 > DRF @action decorator serializer.data 响应问题

问题描述

我在我的视图集中使用@action。

@action(detail=True, methods=('get', 'post', 'put', 'patch'))
def crontab(self, request, pk=None):
    template_obj = self.get_object()

    app_name = template_obj.application.name
    template_name = template_obj.name
    periodic_task_name = '%s:%s' % (app_name, template_name)

    if request.method == 'GET':
        periodic_task = PeriodicTask.objects.filter(
                            name=periodic_task_name)
        if periodic_task.exists():
            crontab_obj = periodic_task.get().crontab
            serializer = serializers.CrontabScheduleSerializer(crontab_obj)
            return Response(serializer.data)
        return Response({'crontab': 'crontab does not exist'})

当条件if periodic_task.exists():为 True 并返回Response(serializer.data)执行时,我收到与 TemplateSerializer 相关的此错误。这个序列化程序在 ViewSet 中使用,而不是在我的 crontab 操作中使用,并且我不会以任何方式触及“应用程序”字段。有什么建议么? 在此处输入图像描述

标签: pythonpython-3.xdjango-rest-framework

解决方案


解决方案。将@action 中的逻辑放入具有相同 URL + '/your_action_name/' 的单独视图中。

还。可以在你的@action 中做这样的事情,但这并不完全正确:

if periodic_task.exists():
    crontab_obj = periodic_task.get().crontab
    serializer = serializers.CrontabScheduleSerializer(crontab_obj)
    res_data = {**serializer.data}
    return Response(res_data)

推荐阅读