Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: More pythonic __unicode__

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 ?

like image 796
Agrajag Avatar asked Nov 09 '12 09:11

Agrajag


1 Answers

% string formatting doesn't support attribute access, but format (since 2.6) does:

def __unicode__(self):
    return u'Unit: {name:s} -- {base.name:s} * {mul:f}'.format(**self.__dict__)
like image 119
ecatmur Avatar answered Nov 19 '22 19:11

ecatmur