handling field DoesNotExist error within a model class

95 views
Skip to first unread message

Rick Shory

unread,
Nov 1, 2013, 12:46:21 PM11/1/13
to django...@googlegroups.com
 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.
 For example:

    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 = ''

 I've tried various formats for that "except" line, such as:
        except DoesNotExist:
        except self.field.rel.to.DoesNotExist:
        except self.DoesNotExist:

 I can use the general:
        except:
 But I need to learn how to do this.


Simon Charette

unread,
Nov 1, 2013, 2:01:45 PM11/1/13
to django...@googlegroups.com
Use the `DateTypeModelClass.DoesNotExist` exception.

By the way, make sure you use `select_related()` if you want to use `__unicode__` on those instances or it will results in 1 + N * 6 queries where N = `Channel.objects.count()`.
Reply all
Reply to author
Forward
0 new messages