0

我几乎在每个模型中都有 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 长度 (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”在未定义时被视为模型字段。

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

4

1 回答 1

3

uuid_length子类中创建一个类变量,因此:

class SomeModel(BaseUuid, SomeOtherMixin):

    uuid_length = 20 // or whatever...

    ...

基类方法中的引用将self.uuid_length按照您的意图引用子类。saveuuid_length

于 2012-10-28T22:50:16.120 回答