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?
JavaScript
x
3
1
if self.model has property documents:
2
context['documents'] = self.get_object().documents.()
3
Advertisement
Answer
You can use hasattr()
to check to see if model has the documents property.
JavaScript
1
3
1
if hasattr(self.model, 'documents'):
2
doStuff(self.model.documents)
3
However, this answer points out that some people feel the “easier to ask for forgiveness than permission” approach is better practice.
JavaScript
1
5
1
try:
2
doStuff(self.model.documents)
3
except AttributeError:
4
otherStuff()
5