[Answered ]-Django rest framework Detail not found while deleting

1👍

First thing – let’s change get_queryset to get_object, because you want single object. Then instead of answer_id=self.kwargs['pk'] simplify it to answer=self.kwargs['pk'].

Another thing – I think it’s might be better to delete old vote while creating new one. You don’t need serializer or special view for that. Just add to function creating new Vote object in your view:

class VoteCreate(...):
    ...
    def perform_create_kwargs(self, **kwargs):
        answer_id = self.kwargs['pk']
        answer = Answer.object.get(id=int(answer_id))

        if Vote.objects.filter(user=self.request.user, answer=answer).exists():
            old_vote = Vote.objects.get(user=self.request.user, answer=answer)
            answer.number_of_points -= old_vote.score
            answer.save()
            old_vote.delete()

        return super().perform_create_kwargs(user=self.request.user, answer_id=answer_id, **kwargs)

Leave a comment