Jives Jives - 15 days ago 6
Python Question

how do i delete a users message without query error?

I am having trouble with my page redirect when deleting a users comment. below is my code. It deletes the message but gives me this error: Message matching query does not exist for Message.objects.get(id=message_id).delete().

def remove_message(request, message_id):
Message.objects.get(id=message_id).delete()
return redirect(reverse('dashboard:show'))

Answer

Instead of get, you can use filter which returns QuerySet. Unlike the get method, the filter does not raise ObjectDoesNotExist exception, but just returns a empty queryset if there's no matching object.

Deleting empty queryset has no harm.

So you the line can be replaced with:

Message.objects.filter(id=message_id).delete()
Comments