Getting 404 not found when trying to update data using a query in Django

Viewed 31

I'm trying to add a status in one of the DB table field where first I'm checking whether the passed ID is present in the table if yes then add.

The ID is basically coming from the API path variable which I'm fetching and passing to the query. Below is the API which I'm using to call the class view.

 "/notify/<int:pk>/mark_as_seen/"

 "/notify/1/mark_as_seen/" # where 1 is the record Id in the DB table

Below is the code which is querying the DB table and checks whether the passed Id is available.

class MarkAsSeenView(BaseAuthenticationMixin, generics.RetrieveAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = SeenSerializer
queryset = Seen.objects.all()

def filter_queryset(self, queryset):
    qs = super().filter_queryset(queryset=queryset)
    qs = qs.exclude(seen_by_user=self.request.user).exclude(user=self.request.user)
    return qs

def retrieve(self, request, *args, **kwargs):
    obj = self.get_object()
    obj.seen_by_user.add(self.request.user)
    return super().get(request, *args, **kwargs)

Now when I'm calling this View via the above API it works perfectly in the first place where it will add one entry in the table as seen with the user id. Now the issue is after performing all the expected things it again going into the filter_queryset method and trying to search the same ID again which was already excluded in the previous iteration due to which it didn't get the same ID let say 1 record in the table results into a 404 not found as a response.

I'm not getting why it is going back again to search the same thing from retrieve to filter_queryset. Can anyone please highlight what is the exact issue here because I have debugged the whole view but not getting why it is jumping thru and fro.

Any kind of help would be much appreciated. Thanks in advance.

1 Answers

I think this line might be the problem and might re-trigger the filter queryset due to calling the get endpoint from the beginning

return super().get(request, *args, **kwargs)

Could you try the following?

def retrieve(self, request, *args, **kwargs):
    obj = self.get_object()
    obj.seen_by_user.add(self.request.user)
    serializer = self.get_serializer(obj)
    return Response(serializer.data)
Related