I have a model "Channel" with various foreign key fields (e.g. "data_type" below).
I have a __unicode__ method to give intelligible information about the model instance by pulling in the foreign key info.
def __unicode__(self):
...
t = self.data_type
...
return u'%s,%s,%s,%s,%s,%s' % (c, l, s, t, u, o)
(Each of the foreign key models have their own __unicode__ method.)
This works fine, unless the instance is incomplete:
>>> c = Channel(column = 3)
>>> c
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 421, in __
repr__
u = six.text_type(self)
File "C:\...\models.py", line 42, in __unicode__
t = self.data_type
File "C:\Python27\lib\site-packages\django\db\models\fields\related.py", line
389, in __get__
raise self.field.rel.to.DoesNotExist
DoesNotExist
How would I correctly write the error handling? This does not quite work:
try:
t = self.data_type
except self.data_type.DoesNotExist:
t = ''
But I need to learn how to do this.