我试图在一般函数中获取文档属性,但是一些模型可能没有文档属性.有没有办法首先检查模型是否具有documents属性,然后有条件地运行代码?
if self.model has property documents:
context['documents'] = self.get_object().documents.()
Run Code Online (Sandbox Code Playgroud)
小智 28
您可以使用hasattr()检查模型是否具有documents属性.
if hasattr(self.model, 'documents'):
doStuff(self.model.documents)
Run Code Online (Sandbox Code Playgroud)
然而,这个答案指出,有些人认为"更容易请求宽恕而不是许可"的方法是更好的做法.
try:
doStuff(self.model.documents)
except AttributeError:
otherStuff()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18138 次 |
| 最近记录: |