Django抽象模型具有接受参数的灵活性

时间:2012-10-28 22:33:21

标签: django model uuid

我几乎每个模特都有uuid字段。为了避免冗余,我有这个BaseUuid抽象模型来生成随机uuid字段:

class BaseUuid(models.Model):  # base abstract model with uuid field
    class Meta:
        abstract = True

    uuid = models.CharField(max_length=22, unique=True)

    def save(self, *args, **kwargs):
        if not self.uuid:
            uuid = shortuuid.uuid()[:10]
            while self.__class__.objects.filter(uuid=uuid).exists():
                uuid = shortuuid.uuid()[:10]
            self.uuid = uuid
        super(BaseUuid, self).save(*args, **kwargs)

正如人们可能注意到的,上面的代码有一个固定的uuid lengh(10)。

现在我想灵活地设置这个长度。我想要这样的东西:

class BaseUuid(models.Model):  # base abstract model with uuid field
    class Meta:
        abstract = True

    uuid = models.CharField(max_length=22, unique=True)

    def __init__(self, uuid_length=10, *args, **kwargs):
        super(BaseUuid, self).__init__(*args, **kwargs)
        self.uuid_length = 22 if uuid_length > 22 else 5 if uuid_length < 5 else uuid_length

    def save(self, *args, **kwargs):
        if not self.uuid:
            uuid = shortuuid.uuid()[:self.uuid_length]
            while self.__class__.objects.filter(uuid=uuid).exists():
                uuid = shortuuid.uuid()[:self.uuid_length]
            self.uuid = uuid
        super(BaseUuid, self).save(*args, **kwargs)

想法是启用uuid_length参数:

class SomeModel(BaseUuid(uuid_length=6), SomeOtherMixin):
    ...

但它似乎不起作用。由于BaseUuid是来自models.Model的子类,因此“self.uuid_length”被视为模型字段,而未定义。

我想知道我应该使用哪些其他变通方法/技术?感谢。

1 个答案:

答案 0 :(得分:3)

使uuid_length成为子类中的类变量,因此:

class SomeModel(BaseUuid, SomeOtherMixin):

    uuid_length = 20 // or whatever...

    ...

基类的self.uuid_length方法中对save的引用将引用您想要的子类uuid_length