mark as read when a product order is views with id. In Django rest framework

36 views Asked by At

This is my models

class Notification(models.Model):
    is_read = models.BooleanField(default=False)

and this is my views


class NotificationListCreateView(generics.ListCreateAPIView):
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer


class NotificationDetailView(generics.RetrieveUpdateAPIView):
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer

In my NotificationDetailView I want to add functionality when a notification views in detail the is_read field should True.

1

There are 1 answers

0
willeM_ Van Onsem On

Update the item with:

class NotificationDetailView(generics.RetrieveUpdateAPIView):
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer

    def get_object(self):
        item = super().get_object()
        item.is_read = True
        item.save(update_fields=('is_read',))
        return item

this will set the item on is_read before serializing it. We can also do this after serializing it with:

class NotificationDetailView(generics.RetrieveUpdateAPIView):
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer

    def retrieve(self, *args, **kwargs):
        response = return super().retrieve(*args, **kwargs)
        item = self.get_object()
        item.is_read = True
        item.save(update_fields=('is_read',))
        return response

but this will make one additiona query.