Optional Unicode Return Values

Created on Dec. 15, 2012, 9:33 a.m. by Hevok & updated by Hevok on May 2, 2013, 5:25 p.m.

The __unicode__() method of a model can return optional values. For instance, if the values need to be returned from other models.

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

Alternatively:

def __unicode__(self):
    ";".join([unicode(x) for x in (thing_a, thing_b, getattr(obj, "optional_attribute", None), ...etc...) if x is not None])
values.jpg

Tags: rest, django, models
Categories: Tutorial, reST
Parent: Web Framework

Update entry (Admin) | See changes

Comment on This Data Unit