Python Django如何检查对象是否具有属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12906933/
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 how to check if the object has property in view
提问by Mirage
I am trying to get the documents property in a general function, but a few models may not have the documents attribute. Is there any way to first check if a model has the documents property, and then conditionally run code?
我试图在通用函数中获取文档属性,但一些模型可能没有文档属性。有没有办法先检查模型是否具有文档属性,然后有条件地运行代码?
if self.model has property documents:
context['documents'] = self.get_object().documents.()
采纳答案by kaezarrex
You can use hasattr()to check to see if model has the documents property.
您可以使用hasattr()来检查模型是否具有文档属性。
if hasattr(self.model, 'documents'):
doStuff(self.model.documents)
However, this answerpoints out that some people feel the "easier to ask for forgiveness than permission" approach is better practice.
但是,这个答案指出,有些人认为“请求宽恕比许可更容易”的方法是更好的做法。
try:
doStuff(self.model.documents)
except AttributeError:
otherStuff()

