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.()
The keyword after the double underscore ( __ ) in field lookup argument is so called lookup types, there are a lot of built-in lookup types that you can use, of cause you can define custom lookup types when you need, we will tell you how to create custom lookup types in other article.
pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or object_id or whatever. It also provides more consistency if you have models with different primary key fields.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With