Model's optional __unicode__() return values?

22 views
Skip to first unread message

Micky Hulse

unread,
Dec 14, 2012, 5:49:16 PM12/14/12
to django...@googlegroups.com
Hello,

This is probably a dumb question, but...

What's the best way to handle optional __unicode__() return values?

In this situation, I'm wanting to return the __unicode__ values from
other models.

I've found myself doing a lot of this:

def __unicode__(self):
return _(u'%s%s%s') % (self.target, (' | ' if self.page_type else
''), (self.page_type if self.page_type else ''))

Which works, but seems clunky.

I've tried:

return _(u'%s') % ' | '.join(filter(None, (self.target, getattr(self,
'page_type', None))))

But that gives me:

Caught TypeError while rendering: sequence item 0: expected string, Target found

Tips would be appreciated. :)

Thank you!

Cheers,
M

Chris Cogdon

unread,
Dec 14, 2012, 6:41:01 PM12/14/12
to django...@googlegroups.com
The pattern I use is ", ".join ( [ unicode(x) for x in ( thing_a, thing_b, getattr(obj,"optional_attribute",None ), ...etc... ) where x is not None ] )

Chris Cogdon

unread,
Dec 14, 2012, 6:41:42 PM12/14/12
to django...@googlegroups.com
oops... that should be "if x is not None", not "where x is not None"... Clearly I am still half in SQL mode :)

Micky Hulse

unread,
Dec 14, 2012, 7:37:17 PM12/14/12
to django...@googlegroups.com
Hi Chris! Thanks so much for your quick reply, I really appreciate it.

On Fri, Dec 14, 2012 at 3:41 PM, Chris Cogdon <ch...@cogdon.org> wrote:
> oops... that should be "if x is not None", not "where x is not None"...
> Clearly I am still half in SQL mode :)

Sweet!!! Works perfectly:

return ' | '.join ([unicode(x) for x in (self.target, getattr(self,
'page_type', None)) if x is not None])

Much appreciated. :)

Have a nice holiday.

Cheers,
Micky
Reply all
Reply to author
Forward
0 new messages