[Django]-How can i make a 'view_count' in django-rest-framework?

4👍

You would add the increment in the NoticeViewSet.retrieve() method. This is the view method called when you retrieve a single object, so it makes sense. You could also add this to the list view method, but depending on the size of the queryset it could get quite slow.

class NoticeViewSet(viewsets.ModelViewSet):
    serializer_class = NoticeSerializer
    queryset=Notice.objects.order_by('title')

    def retrieve(self, request, *args, **kwargs):
        obj = self.get_object()
        obj.view_count = obj.view_count + 1
        obj.save(update_fields=("view_count", ))
        return super().retrieve(request, *args, **kwargs)

If you want to also count views when Notices are listed then use this class:

class NoticeViewSet(viewsets.ModelViewSet):
    serializer_class = NoticeSerializer
    queryset=Notice.objects.order_by('title')

    def retrieve(self, request, *args, **kwargs):
        obj = self.get_object()
        obj.view_count = obj.view_count + 1
        obj.save(update_fields=("view_count", ))
        return super().retrieve(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        # You could also increment the view count if people see the `Notice` in a listing.
        queryset = self.filter_queryset(self.get_queryset())
        for obj in queryset:
            obj.view_count = obj.view_count + 1
            obj.save(update_fields=("view_count", ))
        return super().list(request, *args, **kwargs

Leave a comment