Inheritance and factory functions in Python and Django

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?

+5
2

create() a @classmethod @staticmethod, , :

@classmethod
def create(cls, *args, **kwargs):
    obj = cls(*args, **kwargs)
    obj.set_defaults()
    return obj

.

+7

, , , BaseElement. . - :

class MyBase(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 save(self):
        if not self.id:
            self.objmodule = unicode(self.__class__.__module__)
            self.objclass = unicode(self.__class__.__name__)
            self.uuid = unicode(uuid4())
        super(self.__class__.__base__, self).save()

class InheritedFromBase(MyBase):
    new_field = models.CharField(max_length=100)

, , , , . InheritedFromBase, , .

+2

All Articles