Home

Django MixIn To Not Define __unicode__ Method @ 2009-01-04 20:11:43
Filed under: Django  Tech  Python 
A lot of the models I make just need to return one instance variable as it's 'name' and defining __unicode__ method for each one just to change the instance variable seemed to be a waste of time. So here is what I did so I can type less.

from django.db import models


class UnicodeReprMixIn(object):
    """
    Adds a unicode representation using self._unicode.
    """

    def __unicode__(self):
        """
        Unocode representation of this instance.
        """
        return unicode(self.__getattribute__(self._unicode))


Here is an example using the class variable name as the Unicode representation...

class Company(models.Model, UnicodeReprMixIn):
    """
    A representation of a comic book company.
    """
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    logo = models.ImageField(upload_to=os.path.join('upload', 'company_logos'))
    url = models.URLField(verify_exists=True)

    _unicode = "name"



 digg it   seed it   del.icio.us   ma.gnolia
Tags:       Log in to post comments.


 
A Django joint.
© 2007-2009 Steve 'Ashcrow' Milner | Studio7designs | Arbutus Photography