Django对象匹配查询不存在

时间:2018-02-27 16:01:39

标签: django python-3.x

我对此代码有疑问,它只是不想传递给except

try:
    tariff = Cost.objects.get(language__name=order.language_destination.name, type__name=order.type.name)
except Cost.DoesNotExist:
    tariff = Cost.objects.get(language__name=order.language_source.name, type__name=order.type.name)
else:
    pass

每次它停在try并且它给了我:

DoesNotExist at /shop/orders/doc/

Cost matching query does not exist.

任何想法为什么它没有得到除了代码?

添加else后的完整追溯:

nternal Server Error: /shop/orders/doc/
Traceback (most recent call last):
  File "crm/application/agency/views.py", line 156, in order_document
    tariff = Cost.objects.get(language__name=order.language_destination.name, type__name=order.type.name)
  File "crm/venv/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "crm/venv/lib/python3.5/site-packages/django/db/models/query.py", line 380, in get
    self.model._meta.object_name
order.models.DoesNotExist: Cost matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "crm/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "crm/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "crm/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "crm/venv/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "crm/application/agency/views.py", line 165, in order_document
    tariff = Cost.objects.get(language__name=order.language_source.name, type__name=order.type.name)
  File "crm/venv/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "crm/venv/lib/python3.5/site-packages/django/db/models/query.py", line 380, in get
    self.model._meta.object_name
order.models.DoesNotExist: Cost matching query does not exist.

1 个答案:

答案 0 :(得分:1)

如果失败,因为“源”不存在“目的地”的任何“对象”。

您可以像这样重写代码:

from django.db.models import Q

q1 = Q(language__name=order.language_destination.name)
q2 = Q(language__name=order.language_source.name)
q3 = Q(type__name=order.type.name)

if Cost.objects.filter( q1&q3 ).exists():
    tariff = Cost.objects.get( q1&q3 )
elif Cost.objects.filter( q2&q3 ).exists():
    tariff = Cost.objects.get( q2&q3 )
else:
    *** NOT FOUND ***

但这只是审美变化以避免异常。使用first()

可能是一种更优雅,更快捷的方法
tariff = ( Cost.objects.filter( q1&q3 ).first() or
           Cost.objects.filter( q2&q3 ).first()
         )

if not tariff:
    *** NOT FOUND ***