python获取类名__qualname__,解决django接口ObjectDoesNotExist异常寻找model的问题

在django项目中,经常使用类似Model.objects.get(id=1)的方法取对象,默认抛出的异常是ObjectDoesNotExist类型,通过try catch可以把异常捕获,获取的异常是Model.DoesNotExist类型,

要获知其类名,可以使用__name__方法

要获知其完整类名,可以使用__qualname__方法

还想要获取定义类的路径,可以使用__module__方法

参考文章: https://blog.csdn.net/NeverLate_gogogo/article/details/107519919

python 复制代码
from django.core.exceptions import ObjectDoesNotExist
from variable.models import Variable
a=ObjectDoesNotExist('变量不存在')
b=Variable.DoesNotExist('变量不存在')
try:
    Variable.objects.get(id=0)
except ObjectDoesNotExist as e:
    c = e

In[3]: a.__class__
Out[3]: django.core.exceptions.ObjectDoesNotExist
In[4]: b.__class__
Out[4]: variable.models.Variable.DoesNotExist
In[5]: c.__class__
Out[5]: variable.models.Variable.DoesNotExist
In[6]: a.__class__.__name__
Out[6]: 'ObjectDoesNotExist'
In[7]: a.__class__.__qualname__
Out[7]: 'ObjectDoesNotExist'
In[8]: a.__class__.__module__
Out[8]: 'django.core.exceptions'
In[9]: b.__class__.__name__
Out[9]: 'DoesNotExist'
In[10]: b.__class__.__qualname__
Out[10]: 'Variable.DoesNotExist'
In[11]: b.__class__.__module__
Out[11]: 'variable.models'
相关推荐
锋行天下3 小时前
langgraph 后端发自定义数据,前端接收方法概括
人工智能·python
benchmark_cc4 小时前
用 QuantDash 读取单只股票五档盘口:抽样、缺失值检查与复现记录
python·数据分析·pandas·量化交易·股票数据·quantdash
曲径海盗5 小时前
【Python 学习第 55 天】列表基础
python·学习笔记·编程入门
专注仿真5 小时前
知识问答模型用到的算法集详解及代码实例
python·算法·代码·大模型训练·控制算法
jyOverQ5 小时前
我写了一个 CSDN Markdown 图片助手:告别本地图片逐张上传
python·工具·csdn
刘马想放假9 小时前
CANviz 使用指南|Linux 安装、DBC 解码、实时曲线与 J1939 实战
linux·python·websocket
2601_967987379 小时前
python判断变量名不要调用任何函数实现
python·函数·语法·判断·变量名
卷无止境10 小时前
SALib敏感性分析的python库学习笔记
后端·python
duansamve11 小时前
Python3+Flask+PostgreSQL18+Vue3项目生产环境用docker如何部署?
python·docker·flask
特立独行的猫A12 小时前
少 3 个环节、少 1 次 ABI、少 3500 行代码:cj-tauri 与 Ionic/Capacitor 的鸿蒙桥接机制对比
java·后端·python