Search code examples
djangodjango-modelsdjango-managers

How do i modify my create function in Django model manager


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?


Solution

  • 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)