Mirage
Mirage

Reputation: 31548

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

Upvotes: 28

Views: 35497

Answers (2)

cottontail
cottontail

Reputation: 23051

You can also use getattr with a default value if the property doesn't exist.

getattr(self.model, "documents", "default")

This returns the documents property if it exists and returns "default" otherwise. So it does a little more than hasattr because hasattr only checks if a property exists while getattr gets the property if it exists.

So you can do something like:

if (docs := getattr(self.model, "documents", None)) is not None:
    doStuff(docs)
else:
    otherStuff()

Also, one problem (that doesn't exist with getattr) with the try-except block in @kaezarrex's answer is that it doesn't distinguish whether the AttributeError was raised due to self.model.documents or some other bug inside doStuff(). It might be better to use the following instead so that otherStuff is called only when documents attribute doesn't exist in self.model.

try:
    docs = self.model.documents
except AttributeError:
    otherStuff()
else:
    doStuff(docs)

Upvotes: 0

kaezarrex
kaezarrex

Reputation: 1316

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

Upvotes: 58

Related Questions