24

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.()
Chris
  • 26,361
  • 5
  • 21
  • 42
Mirage
  • 30,868
  • 62
  • 166
  • 261
  • Why are you ever using a model that doesn't have it there? – Ignacio Vazquez-Abrams Oct 16 '12 at 03:09
  • I have generic view which displays all the models in single template. Initially i didn't have any documents but now few of them has documents attached. so i was thinking if there is some way to check othwise , i need to define the new view with 90% same code. For hackish solution i have made a function with try and except so that i don't get any error in site but was looking for proper way – Mirage Oct 16 '12 at 03:37
  • Why don't you have the model tell which view it should use, with a sane default? – Ignacio Vazquez-Abrams Oct 16 '12 at 03:54

1 Answers1

52

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()
Community
  • 1
  • 1
kaezarrex
  • 1,246
  • 11
  • 8