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
- [Django]-Error apache configuration error: couldn't perform authentication. AuthType not set!: / on centos 6
- [Django]-Django QuerySet querying or filtering "Odd" and/or "Even" value in a particular field
- [Django]-Django – Redirect user to "next" parameter after successful login
- [Django]-Django cannot find my templatetags, even though it's in INSTALLED_APPS and has a __init__.py
- [Django]-How to find duplicate records based on certain fields in Django
Source:stackexchange.com