I am creating a Django application that uses some inheritance in the model, mainly because I need to assign all the UUIDs and the link so that I know which class was. Here's a simplified version of the base class:
class BaseElement(models.Model):
uuid = models.CharField(max_length=64, editable=False, blank=True, default=lambda:unicode(uuid4()))
objmodule = models.CharField(max_length=255, editable=False, blank=False)
objclass = models.CharField(max_length=255, editable=False, blank=False)
class ChildElement(BaseElement):
somefield = models.CharField(max_length=255)
I would like to make sure objmodule, objclass and uuid are installed automatically. I learned from this post that it is a bad idea to do this by writing my own constructor and that I better write a factory function. So now my BaseElement and ChildElement looks like this:
class BaseElement(models.Model):
uuid = models.CharField(max_length=64, editable=False, blank=True, default=lambda:unicode(uuid4()))
objmodule = models.CharField(max_length=255, editable=False, blank=False)
objclass = models.CharField(max_length=255, editable=False, blank=False)
def set_defaults(self):
self.objmodule = unicode(self.__class__.__module__)
self.objclass = unicode(self.__class__.__name__)
self.uuid = unicode(uuid4())
class ChildElement(BaseElement):
somefield = models.CharField(max_length=255)
@staticmethod
def create(*args, **kwargs):
ce = ChildElement(*args, **kwargs)
ce.set_defaults()
return ce
. ChildElement.create(somefield="foo"), uuid, objmodule objclass. , , , ChildElement2 ChildElement3, , factory. , .
create factory BaseElement, , ( ), , .
factory BaseElement, , uuid, objmodule, objclass?