我正在尝试找出如何将额外的参数传递给序列化器。
我的情况是这样的:
class ActivityDataHours(generics.RetrieveUpdateAPIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, *args, **kwargs):
pa = ProjectActivity.objects.values('project_code').distinct()
if request.GET.get('activityCode') is not None:
is_code_filter = False
else:
is_code_filter = True
return Response(ActivityDataHoursSerializer(pa, many=True, context={'is_code_filter': is_code_filter}).data)
class ActivityDataHoursSerializer(serializers.ModelSerializer):
activity_hours = serializers.SerializerMethodField()
@staticmethod
def get_activity_hours(self, project_activity):
is_code_filter = self.context.get("is_code_filter")
wh = WorkedHours.objects.values('project_code')
return wh
class Meta:
model = Project
fields = ['activity_hours']
答案已经可用:Pass extra arguments to Serializer Class in Django Rest Framework
但是我不明白如何使用self参数。
出现在我身上的错误是:
TypeError:get_activity_hours()缺少1个位置参数 必需:“ project_activity”
答案 0 :(得分:1)
删除 @staticmethod
即可完成工作!