Python 姜戈不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16181188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django DoesNotExist
提问by Carlos
I am having issues on trying to figure "DoesNotExist Errors", I have tried to find the right way for manage the no answer results, however I continue having issues on "DoesNotExist" or "Object hast not Attribute DoestNotExists"
我在尝试计算“DoesNotExist 错误”时遇到问题,我试图找到管理无应答结果的正确方法,但是我仍然遇到“DoesNotExist”或“对象没有属性不存在”的问题
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')
采纳答案by Carlos
I have found the solution to this issue using ObjectDoesNotExist on this way
我以这种方式使用 ObjectDoesNotExist 找到了解决此问题的方法
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
无论如何,谢谢你的帖子帮助我解决了我的问题
回答by Dmitry Shevchenko
This line
这条线
except Vehicle.vehicledevice.device.DoesNotExist
means look for device instancefor DoesNotExist exception, but there's none, because it's on class level, you want something like
意味着寻找DoesNotExist异常的设备实例,但没有,因为它在类级别,你想要类似的东西
except Device.DoesNotExist
回答by Syed_Shahiq
The solution that i believe is best and optimized is:
我认为最好和优化的解决方案是:
try: #your code except "ModelName".DoesNotExist: #your code

