Django DoesNotExist

时间:2013-04-24 00:06:30

标签: python django django-models django-views

我在尝试查找“DoesNotExist Errors”时遇到问题,我试图找到管理无应答结果的正确方法,但是我继续遇到“DoesNotExist”或“Object没有属性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')

4 个答案:

答案 0 :(得分:108)

这一行

 except Vehicle.vehicledevice.device.DoesNotExist

意味着为DoesNotExist异常寻找设备实例,但是没有,因为它在类级别上,你想要像

这样的东西
 except Device.DoesNotExist

答案 1 :(得分:79)

我已经通过这种方式使用ObjectDoesNotExist找到了解决这个问题的方法

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

try:
  # try something
except ObjectDoesNotExist:
  # do something

在此之后,我的代码可以正常工作

非常感谢,你的帖子帮我解决了我的问题

答案 2 :(得分:0)

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

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

答案 3 :(得分:-1)

第一种方式:

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)