Reputation: 6590
I'm dealing with some django code in which all models have __unicode__
methods that look something like this:
def __unicode__(self):
return str(self.id) + "; " + ", " + self.first_name + " " + self.last_name
(the format in all cases being: print self.id
and then the rest of the fields separated by commas). What's the best way to clean up this sort of boilerplate? I was thinking of declaring a MyModel
class with a __unicode__
method which lists all fields by inspection, and then having all my current models inherit from MyModel
instead of the current django.db.models.Model
. But doing so would change the underlying MySQL tables and I'd hate to have to do such a massive migration for a petty thing like this.
Upvotes: 2
Views: 139
Reputation: 713
As Kevin Christopher Henry suggested, you could create an abstract base class and let all your models inherit that. This would work fine.
However, Python supports multiple class inheritance. This means that a class can inherit from more than one base class. For more information on this subject (and I recommend you read it since it can be tricky) can be found here.
With multiple class inheritance you are able to create a solution that is, at least in my eyes, a lot cleaner. You simply create a class that only has the required code:
class PredefinedUnicodeMixin(object):
def __unicode__(self):
return str(self.id) + "; " + ", " + self.first_name + " " + self.last_name
As you might imagine, using this class on its own would not be very helpful. But try this:
class MyModel(PredefinedUnicodeMixin, models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
Because our mixin class is listed first, it overrides any attributes and methods that are specified in the other classes.
Changing your __unicode__
method to iterate over the fields is not that hard, self._meta.get_all_field_names()
should contain all field names.
Of course, on Python 3 you shoud use __str__
instead of __unicode__
.
Upvotes: 6