python - 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 操作中使用,并且我不会以任何方式触及“应用程序”字段。有什么建议么?
解决方案
解决方案。将@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)
推荐阅读
- git - 本地目录和远程存储库之间的连接丢失
- azure - 带有 Ubuntu 14.04 32 位的 azure 管道自定义代理
- sql-server - Laravel:带有绑定参数的原始查询的空结果
- python - 如何从 AWS Python Lambda 获取响应
- javascript - 如何在 Mongoose 中组合两个模式?
- pandas - 熊猫在将列表添加到系列时出错
- javascript - 清除先前的 GeoJSON 对象
- amazon-web-services - 存储位置以及如何计算用户指标
- javascript - 在 null 上调用成员函数 move() (Rest api laravel)
- sql - 停止处理存储过程