[Answered ]-Get Old Objects, Update, and then return old objects

1πŸ‘

βœ…

however, my current code returns the objects after updating them. I want to return the old objects prior to updating hence me assigning notifications to the old objects before updating. I believe this is due to lazy loading on Django’s part. Is there a way/better way to solve this?

It will still return the updated objects, since the query will, if ever, be evaluated after the update, and hence at that time is_read will already be set to True.

You should "materialize" the queryset, so forcing to load it into memory. For example by calling list(…) on it:

class GetNotifications(ListAPIView):
    serializer_class = NotificationSerializer

    def get_queryset(self):
        notifications = (
            Notification.objects.select_related()
            .filter(user=self.request.user)
            .order_by('-created_at')
        )
        list(notifications)
        Notification.objects.filter(user=self.request.user).update(is_read=True)
        return notifications

Leave a comment