Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to check if the object has property in view

Tags:

python

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.()
like image 677
Mirage Avatar asked Oct 16 '12 03:10

Mirage


People also ask

What does __ in do in Django?

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.

What is PK and ID in Django?

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.


1 Answers

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()
like image 156
kaezarrex Avatar answered Sep 23 '22 04:09

kaezarrex