0

So i have this model:

class Token(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False)
    code = models.IntegerField(default=code)
    date_created = models.DateTimeField(auto_now_add=True)
    expiration_date = models.DateTimeField(null=False, blank=True)

as you can see I have an expiration_date field. The reason why I set it to (null=False, blank=True) is because I want it to fill itself based of the date_created field, and I'm trying to do that from the model manager create method

I have little to no experience in model manager outside of custom user model manager. Here's my first failed attempt:

class TokenManager(models.Manager):

    def create(self, user, code, date_created):

        exp = date_created + datetime.timedelta(minutes=10)

        token = self.model(user=user, code=code, date_created=date_created, expiration_date=exp)

        token.save()

        return token

basically my goal here is to get the value of date_created field, add the value by 10 minutes and set it as the expiration_date. can anyone help me with this?

Melly
  • 675
  • 8
  • 24

1 Answers1

1

There is no need to use a ModelManger here. You can just set the expiration_date based on the field date_created by overwriting the save method.

Edit: It is not possible to use self.date_created datetime within the save method. However it is possible to use django.utils.timezone.now()which is also used by auto_now_add .

from django.utils import timezone

class Token(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False)
    code = models.IntegerField(default=code)
    date_created = models.DateTimeField(auto_now_add=True)
    expiration_date = models.DateTimeField(null=False, blank=True)
    
    def save(self, *args, **kwargs):
        # Set the expiration_date based on the value of auto_now_add
        self.expiration_date  = timezone.now() + datetime.timedelta(minutes=10)
        super(Token, self).save(*args, **kwargs)

Helge Schneider
  • 483
  • 5
  • 8
  • I got an error that says `unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'` – Melly Mar 01 '22 at 12:53
  • I didn't know that an auto_now_add field cannot be accessed in the save() method. I edited the answer accordingly. – Helge Schneider Mar 01 '22 at 13:17
  • May I ask why did the super method in our custom save function need the `Token` model and `self` as the parameters? – Melly Mar 01 '22 at 14:23
  • You can read more about the `super` method and it's usage in [this answer](https://stackoverflow.com/a/27134600/15353043). – Helge Schneider Mar 02 '22 at 07:31