All my django-models have unicode functions, at the moment these tend to be written like this:
def __unicode__(self):
return u'Unit: %s -- %s * %f' % (self.name, self.base.name, self.mul)
However, Code Like a Pythonista, at http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#string-formatting points out that self.__dict__ is a dictionary, and as such the above can be simplified to:
def __unicode__(self):
return u'Unit: %(name)s -- %(base.name)s * %(mul)f' % self.__dict__
This works, except for the “base.name”, because python tries to look up self.__dict__['base.name'] which fails, while self.base.name works.
Is there an elegant way of making this work, even when you need to follow foreign-key-relationships ?
%string formatting doesn’t support attribute access, butformat(since 2.6) does: