Skip to content
Advertisement

How to check if the object has property in view in Django?

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.()

Advertisement

Answer

You can use hasattr() to check to see if model has the documents property.

if hasattr(self.model, 'documents'):
    doStuff(self.model.documents)

However, this answer points 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()
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement