Django:从继承的模型内部覆盖抽象模型的方法模型



我有一个问题,重新分配一些var在我的模型,我有一个这样的模型:

class ExpireTime(models.Model):
"""Expire time fields and methods in abstract mode"""

def expire_time():
return create_expire_time(seconds=10)
expire = models.DateTimeField(default=expire_time)
def is_expired(self) -> bool:
return self.expire < timezone.now()
class Meta:
abstract = True

但是在使用这个抽象模型的不同模型中,我需要在expe_time:

中使用不同的过期时间
def expire_time():
return create_expire_time(seconds=10)

所以我试图在从ExpireTime继承的模型中覆盖此方法,但它没有效果。

那么我该如何解决这种情况呢?在这种情况下,我不应该使用抽象模型吗?

:

继承自ExpireTime:

的模型
class TempLink(ExpireTime, models.Model):
"""Temp link for provide some files with security"""
# Needs 10 sec expiration time 
link = models.UUIDField(
primary_key=True, default=uuid4, editable=False, unique=True
)
ip = models.GenericIPAddressField()
file = models.FileField()
def is_valid_ip(self, ip: models.GenericIPAddressField) -> bool:
return ip == self.ip

class UserConfirm(ExpireTime, models.Model):
"""confirm user activate wiht random code"""
# needs 120 sec expiration time 
LENGTH_CODE: int = 5
# Generate Random Code Between 0 to 9
def generate_code() -> str:
code = "".join(
[str(random.randint(0, 9)) for _ in range(UserConfirm.LENGTH_CODE)]
)
return code
user = models.OneToOneField(NewUser, on_delete=models.CASCADE)
code = models.CharField(max_length=LENGTH_CODE, default=generate_code, unique=True)
token = models.UUIDField(default=uuid4, unique=True)
def is_valid_code(self, input_code):
return input_code == self.code

你可以在save:

class ExpireTime(models.Model):
default_expired = 10
expire = models.DateTimeField(null=True, blank=true)
class Meta:
abstract = True
def save(self, *args, **kwargs):
if not self.expire:
self.expire = create_expire_time(seconds=self.default_expired)
super().save(*args, **kwargs)

class OtherExpireTime(ExpireTime):
default_expired = 20

相关内容

  • 没有找到相关文章

最新更新