Here is a Django model I'm using.
class Person(models.Model):
surname = models.CharField(max_length=255, null=True, blank=True)
first_name = models.CharField(max_length=255, null=True, blank=True)
middle_names = models.CharField(max_length=255, null=True, blank=True)
birth_year = WideYear(null=True, blank=True)
birth_year_uncertain = models.BooleanField()
death_year = WideYear(null=True, blank=True)
death_year_uncertain = models.BooleanField()
flourit_year = WideYear(null=True, blank=True)
flourit_year_uncertain = models.BooleanField()
FLOURIT_CHOICES = (
(u'D', u'Birth and death dates'),
(u'F', u'Flourit date'),
)
use_flourit = models.CharField('Date(s) to use', max_length=2, choices=FLOURIT_CHOICES)
def __unicode__(self):
if str(self.birth_year) == 'None':
self.birth_year = ''
if str(self.death_year) == 'None':
self.death_year = ''
if str(self.flourit_year) == 'None':
self.flourit_year = ''
if self.use_flourit == u'D':
return '%s, %s %s (%s - %s)' % (self.surname, self.first_name, self.middle_names, self.birth_year, self.death_year)
else:
return '%s, %s %s (fl. %s)' % (self.surname, self.first_name, self.middle_names, self.flourit_year)
This bit of code from the model's __unicode__ method seems rather verbose:
if str(self.birth_year) == 'None':
self.birth_year = ''
if str(self.death_year) == 'None':
self.death_year = ''
if str(self.flourit_year) == 'None':
self.flourit_year = ''
Its aim is to stop the __unicode__ method from returning something like
Murdoch, Rupert (1931 - None)
and to ensure the method instead returns something like
Murdoch, Rupert (1931 - )
Is there a way to "glob" that bit of code somehow, e.g. using a wildcard so that all attributes of the self object are processed?
Something like this:
if str(self.(*)) == 'None':
self.$1 = ''
Here, I've just used regular expression syntax to illustrate what I mean; obviously, it's not working python code. Essentially the idea is to loop through each of the attributes, checking if their str() representations are equal to 'None' and if so, setting them to ''. But it would be nice if this could be done more concisely than by setting up a for loop.