Model matching query does not exist.

I guys,
I´m making a polling and that view is making a query like Record.objects.filter(is_read = False).first(), and its normal that the query often does not get results and as it is normal it gives a 500 error.
I’ve been researching and found this solution:

from django.shortcuts import get_object_or_404

comment = get_object_or_404(Comment, pk=comment_id)

And it works, but my question is, is it the best way to do it? this is an ajax request so I don’t need to return a 404. Is there a different way or is this a good solution?

Best regards Gonçalo Marques

If you’re getting a 500 response, it’s not because of this query. It’s perfectly valid for a query to return a zero-length queryset. Any 500 error you are receiving is because of some other code in that view.

“Best” is a relative term, not an absolute. There is no “best” outside the context of the overall objectives for that view.

A 404 can be useful in the context of an AJAX request. Just because a request is issued AJAX-style does not necessarily mean that the return codes aren’t useful. It’s an issue of what your client wants to do with that information provided by those codes.

Yes, there are different ways. As stated above, your first query is valid. It’s something else in the view causing the 500.

Yes, the get_object_or_404 is also a good solution.

Its not returning query set, its returning a object, i use first() in the query, i only need the first match by that query.

record = Record.objects.filter(is_read = False).first()

True, in this case it would return None if the filter resulted in an empty queryset.

It’s still a valid query and by itself would not cause a 500 error.

Oh true i found the error =) but thanks for the info about get_object_or_404

Best regards