python - Django 使用 try : and except:

标签 python django python-2.7 exception

我想知道是否可以编写一个处理异常的方法,比如处理 2 个或更多异常,但要执行不同的任务。

我正在使用 Django==1.6.1Python 2.7

try:
    foo_instance = foo.objects.get(field_name='unknown')

except foo.DoesNotExist:
    new_rec = foo.objects.create(field_name='unknown')
    new_rec.save()

    foo_instance = foo.objects.get(field_name='unknown')

except foo.MultipleObjectsReturned:
    foo_list = foo.objects.filter(field_name='unknown')
    for record in foo_list[1:]:
       print 'Deleting foo id: ', record.id
       record.delete()

    foo_instance = foo.objects.get(field_name='unknown')

最佳答案

您可以使用多个 try: except: 但在您当前的情况下为什么不使用 get_or_create

try: expect: 包含“Exception”上的所有错误。因为这个语法是全部

except Exception as e:

get_or_create(defaults=None, **kwargs)

A convenience method for looking up an object with the given kwargs (may be empty if your model has defaults for all fields), creating one if necessary.

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

这会将您的上述代码减少为 -

 obj, created = foo.objects.get_or_create(field_name='unknown')
 if created:
     obj.save()

我认为 get_or_create 提高了 IntegrityErrorMultipleObjectsReturned , 处理这些只需尝试将其包装起来:

try:
    obj, created = foo.objects.get_or_create(field_name='unknown')
    if created:
        obj.save()
except IntegrityError: 
    #do something
except MultipleObjectsReturned:
    #do something else
except Exception as e:
    raise e

关于python - Django 使用 try : and except:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23464269/

相关文章:

python - 使用 Pandas 提高时间序列数据的采样率

python - 在将数据放入代码中时使用技巧来拯救程序员是否可以接受?

python - 使用排除时用户对象不可迭代

python - pip 安装安装 channel 时出错

python - fexpect 破坏结构脚本

python - 无效语法 - python

python - 在 Django 中使用 InlineAdmin 和 post_save 信号创建配置文件模型

python - 将大矩阵保存到 python 中的 .txt 文件中

json.dumps() 不工作

python - 如何从 Python 中的函数引用中提取签名?