[Django]-How to handle an exception in Django moving from get() to filter()

5👍

filter() not raise DoesNotExist error. You can catch IndexError to prevent error in case queryset is empty and doesn’t contain any elements:

try:
    record = Record.objects.filter(name__iexact=record_name)[0]
except IndexError:
    logging.debug("Error: Record does not exist")
    return Response({"Error": "Record does not exist"}, status=status.HTTP_404_NOT_FOUND)

Or you can use first() method, which also not raise error. But you can check result with if statement:

record = Record.objects.filter(name__iexact=record_name).first()
if not record:
    logging.debug("Error: Record does not exist")
    return Response({"Error": "Record does not exist"}, 

3👍

You might prefer to use first:

record = Record.objects.filter(name__iexact=record_name).first()
if record is None:
    # record does not exist - handle this

Returns the first object matched by the queryset, or None if there is no matching object. If the QuerySet has no ordering defined, then the queryset is automatically ordered by the primary key.

👤wim

1👍

Use the powers bestowed on you by the queryset API:

record_qs = Record.objects.filter(name__iexact=record_name)
if not record_qs.exists():
    logging.debug("Error: Record does not exist")
    return Response({"Error": "Record does not exist"}, status=status.HTTP_404_NOT_FOUND)
else:
    record = record_qs[0]
    # Do stuff with record.
👤jhrr

Leave a comment