在我非常简单的学习应用程序中,我想在模型变为“完成”时触发一些逻辑。具体来说,我将以下有效负载传递给我的视图集:
{
complete: true
}
如下:
class TestQuestionViewset(viewsets.ModelViewSet):
queryset = TestQuestion.objects.all()
serializer_class = TestQuestionSerializer
我想触发一些逻辑服务器端,一旦完成标记被更新,该逻辑服务器端就会被触发。
我可以覆盖更新方法吗?如果是这样,我该怎么办?
答案 0 :(得分:1)
尝试
class TestQuestionViewset(viewsets.ModelViewSet):
queryset = TestQuestion.objects.all()
serializer_class = TestQuestionSerializer
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
if partial:
old_complete_value = instance.complete
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
if partial and old_complete_value is False:
instance.refresh_from_db()
if instance.complete:
...
# do your logic here
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
return Response(serializer.data)