102

我在尝试找出“DoesNotExist 错误”时遇到问题,我试图找到管理无答案结果的正确方法,但是我继续遇到“DoesNotExist”或“对象没有属性 DoesNotExists”的问题

from django.http import HttpResponse
from django.contrib.sites.models import Site
from django.utils import simplejson

from vehicles.models import *
from gpstracking.models import *


def request_statuses(request):

    data = []
    vehicles = Vehicle.objects.filter()
    Vehicle.vehicledevice_
    for vehicle in vehicles:
        try:
            vehicledevice = vehicle.vehicledevice_set.get(is_joined__exact = True)
            imei = vehicledevice.device.imei
            try:
                lastposition = vehicledevice.device.devicetrack_set.latest('date_time_process')
                altitude = lastposition.altitude
                latitude = lastposition.latitude
                longitude =  lastposition.longitude
                date_time_process = lastposition.date_time_process.strftime("%Y-%m-%d %H:%M:%S"),
                date_time_created = lastposition.created.strftime("%Y-%m-%d %H:%M:%S")
            except Vehicle.vehicledevice.device.DoesNotExist:
                lastposition = None
                altitude = None
                latitude = None
                longitude = None
                date_time_process = None
                date_time_created = None
        except Vehicle.DoesNotExist:
            vehicledevice = None
            imei = ''

        item = [
                vehicle.vehicle_type.name,
                imei,
                altitude,
                "Lat %s Lng %s" % (latitude, longitude),
                date_time_process,
                date_time_created,
                '', 
                ''
                ]
        data.append(item)
    statuses = {
                "sEcho": 1,
                "iTotalRecords": vehicles.count(),
                "iTotalDisplayRecords": vehicles.count(),
                "aaData": data
                } 
    json = simplejson.dumps(statuses)
    return HttpResponse(json, mimetype='application/json')
4

4 回答 4

156

这条线

 except Vehicle.vehicledevice.device.DoesNotExist

表示为 DoesNotExist 异常寻找设备实例,但没有,因为它在类级别,你想要类似的东西

 except Device.DoesNotExist
于 2013-04-24T00:12:40.960 回答
151

我以这种方式使用 ObjectDoesNotExist 找到了解决此问题的方法

from django.core.exceptions import ObjectDoesNotExist
......

try:
  # try something
except ObjectDoesNotExist:
  # do something

在此之后,我的代码按我的需要工作

无论如何,谢谢你的帖子帮助我解决我的问题

于 2013-04-29T21:32:37.470 回答
18

我认为最好和优化的解决方案是:

尝试:
   #你的代码
除了“ModelName”。DoesNotExist:
   #你的代码
于 2019-11-15T07:42:45.953 回答
0

第一种方式:

try:
   # Your code goes here
except Model.DoesNotExist:
   # Handle error here

在 Django 中找不到另一种处理方式。它引发 Http404 而不是模型的 DoesNotExist 异常。

https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#get-object-or-404

from django.shortcuts import get_object_or_404

def get_data(request):
    obj = get_object_or_404(Model, pk=1)
于 2021-01-06T15:30:42.300 回答