姜戈不存在

我在尝试计算“ DoesNotExist 错误”时遇到了问题,我试图找到正确的方法来管理无应答结果,但是我继续遇到“ DoesNotExist”或“ Object hast not Attribute DoestNotExists”的问题

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')
173531 次浏览

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

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


try:
# try something
except ObjectDoesNotExist:
# do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

The solution that i believe is best and optimized is:

try:
#your code
except "ModelName".DoesNotExist:
#your code

First way:

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

Another way to handle not found in Django. It raises Http404 instead of the model’s DoesNotExist exception.

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)