pythondjangodjango-modelsdjango-model-field

How to check if a model object has a given attribute/property/field? (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.()

Solution

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