Home > Blockchain >  Django RetrieveAPIView where is the rights place to do some small db update
Django RetrieveAPIView where is the rights place to do some small db update

Time:10-07

I'm using Django REST framework, and still quite new to it..

I Want to retrieve a message from db with generics.RetrieveAPIView method, which I did.. But I want to also set the read field to true at the database. Where is the place to do it (maybe in the serializer)?

This is the idea:

class MessageDetail(generics.RetrieveAPIView):
  serializer_class = MessageSerializer
  permission_classes = [IsAuthenticated] 
  queryset = AppUserMessage.objects.all()

  AfterTheRequst(self) # This is what I want to do
    obj.read_at = time.now()

CodePudding user response:

You can override the retrieve method, and do the update before sending the reponse.

def retrieve(self, request, *args, **kwargs):
    instance = self.get_object()
    serializer = self.get_serializer(instance)
    if instance:    # check if instace is there 
        instance.read_at = time.now()  # here update
    return Response(serializer.data)
  • Related