get (( 的原始代码
try:
record = Record.objects.get(name__iexact=record_name)
except Record.DoesNotExist:
logging.debug("Error: Record does not exist")
return Response({"Error": "Record does not exist"}, status=status.HTTP_404_NOT_FOUND)
此查询可以返回多个记录,因此我将切换到此
try:
record = Record.objects.filter(name__iexact=record_name)[0]
except Record.DoesNotExist:
logging.debug("Error: Record does not exist")
return Response({"Error": "Record does not exist"}, status=status.HTTP_404_NOT_FOUND)
但是,我的异常处理不起作用。 如果查询返回空列表,如何使异常捕获?
filter()
不会引发DoesNotExist
错误。您可以捕获IndexError
以防止在查询集为空且不包含任何元素的情况下出错:
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)
或者您可以使用first()
方法,该方法也不会引发错误。但是您可以使用if
语句检查结果:
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"},
您可能更喜欢使用first
:
record = Record.objects.filter(name__iexact=record_name).first()
if record is None:
# record does not exist - handle this
返回查询集匹配的第一个对象,如果没有匹配的对象,则返回
None
。 如果 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.