Wednesday, May 25, 2011

Django Models Mixins

One thing I've been experimenting with is model Mixins.  For example, the aim is to create small abstract classes that are each focused around a particular function.  These abstract classes can then be added to arbitrary models to apply those functions to models as desired.

For example, say I define a RatingsFields abstract class and a TrackingFields abstract class.  These abstract classes can be mixed into any other model that we wish to add rating or tracking functionality to.

core/mixins.py
from djangoratings.fields import RatingField # 3rd party module

class RatingFields(models.Model):
    
    rating = RatingField(range=5) # 5 possible rating values, 1-5

    class Meta:
        abstract = True
        

class TrackingFields(models.Model):

    deleted_on = models.DateTimeField(blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True
        

Since we applied the abstract classes to the Post model below, the model now has rating and tracking capabilities.  This is useful to help simplify code where a lot of models share fields or methods with the same function.

myapp/models.py
from core import mixins as core_mixins
class Post(core_mixins.TrackingFields, core_mixins.RatingFields):
    name = models.CharField(max_length=128)
    slug = models.SlugField(max_length=128)
    ...

Comments welcome.
Joe