I have a problem with re-assigning some var in my model, I have a model like this:
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
but in the different models that used this abstract model, I need the use different expiration times in the exprie_time:
def expire_time():
return create_expire_time(seconds=10)
so I am trying to overwrite this method in the model that was inherited from ExpireTime but it has no effect.
so how can I solve this situation? Should I not use the abstract model in this situation?
Update:
the model that was inherited from 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
CodePudding user response:
you can always do it on 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