2009-07-02 18:03:02 +00:00
|
|
|
from django.db import models
|
|
|
|
|
from django.contrib.contenttypes.models import ContentType
|
|
|
|
|
|
2009-07-02 20:14:29 +00:00
|
|
|
from model_utils.fields import AutoCreatedField, AutoLastModifiedField
|
|
|
|
|
|
2009-07-02 18:03:02 +00:00
|
|
|
class InheritanceCastModel(models.Model):
|
|
|
|
|
"""
|
|
|
|
|
An abstract base class that provides a ``real_type`` FK to ContentType.
|
|
|
|
|
|
|
|
|
|
For use in trees of inherited models, to be able to downcast
|
|
|
|
|
parent instances to their child types.
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
real_type = models.ForeignKey(ContentType, editable=False, null=True)
|
2010-04-15 02:43:27 +00:00
|
|
|
|
2009-07-02 18:03:02 +00:00
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
|
if not self.id:
|
|
|
|
|
self.real_type = self._get_real_type()
|
|
|
|
|
super(InheritanceCastModel, self).save(*args, **kwargs)
|
2010-04-15 02:43:27 +00:00
|
|
|
|
2009-07-02 18:03:02 +00:00
|
|
|
def _get_real_type(self):
|
|
|
|
|
return ContentType.objects.get_for_model(type(self))
|
2010-04-15 02:43:27 +00:00
|
|
|
|
2009-07-02 18:03:02 +00:00
|
|
|
def cast(self):
|
|
|
|
|
return self.real_type.get_object_for_this_type(pk=self.pk)
|
2010-04-15 02:43:27 +00:00
|
|
|
|
2009-07-02 18:03:02 +00:00
|
|
|
class Meta:
|
|
|
|
|
abstract = True
|
2009-07-02 20:14:29 +00:00
|
|
|
|
|
|
|
|
|
2010-04-15 02:43:27 +00:00
|
|
|
class TimeStampedModel(models.Model):
|
2009-07-02 20:14:29 +00:00
|
|
|
"""
|
|
|
|
|
An abstract base class model that provides self-updating
|
|
|
|
|
``created`` and ``modified`` fields.
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
created = AutoCreatedField()
|
|
|
|
|
modified = AutoLastModifiedField()
|
|
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
abstract = True
|
|
|
|
|
|