1

我正在使用序列化程序来获取特定资源的相关数据,如下所示:

会话序列化器.py

def to_representation(self, instance):
  response = super().to_representation(instance)
  response["user"] = UserSerializer(instance.user).data
  if instance.experiment:
      response["experiment"] = ExperimentSerializer(instance.experiment).data
  response["last_event"] = EventSerializer(instance.last_global_event).data

  # fetch and return all session answers tied to this session
  response["session_answers"] = instance.sessionanswer_set.values()
  return response

我还在 SessionViewSet 中使用 DRF 缓存装饰器,这似乎工作正常。但是,当实例有更新和/或任何相关实例(如用户)有更新时,我不能使缓存数据无效。

是否有关于如何在更新时清除缓存数据的标准做法或文档?

4

2 回答 2

0

要监听数据库记录的更改并根据它们进行更改,可以使用 django 信号:

https://docs.djangoproject.com/en/3.2/topics/signals/

于 2021-09-13T08:46:42.043 回答
0

我就是这样做的,你会发现并了解更多——我还在学习。这是我的意见.py

from django.core.cache import cache

class stateViewSet(viewsets.ModelViewSet):
    ---
    ---
    def create(self, request, format=None):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            cache.delete('STATE_CACHE_KEY')
            q = state.objects.prefetch_related("states").all()
            cache.set('STATE_CACHE_KEY', q, 2 * 60)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    def list(self, request):
        queryset = cache.get('STATE_CACHE_KEY')
        if queryset is None:
            queryset = self.get_queryset()
            cache.set('STATE_CACHE_KEY', queryset, 2 * 60)
        serializer = self.get_serializer(queryset, many =True)
        return Response(serializer.data)
    def destroy(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
            self.perform_destroy(instance)
            q = state.objects.prefetch_related("states").all()
            cache.delete('STATE_CACHE_KEY')
            cache.set('STATE_CACHE_KEY', q, 2 * 60)
        except Http404:
            pass
        return Response(status=status.HTTP_204_NO_CONTENT)
于 2021-09-13T07:23:55.527 回答