如何处理Django中从get()移动到filter()的异常

时间:2018-05-21 16:51:43

标签: django

原始代码与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)

然而,我的异常处理不起作用。如果查询返回空列表,如何进行异常捕获?

3 个答案:

答案 0 :(得分:2)

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"}, 

答案 1 :(得分:2)

您可能更喜欢使用first

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

返回查询集匹配的第一个对象,如果没有匹配的对象,则返回None。如果QuerySet没有定义排序,那么查询集将由主键自动排序。

答案 2 :(得分:1)

使用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.