Wizard
Wizard

Reputation: 22043

Deal with timedelta () and datetime.now

I'd like to set timedelta for a data model

class ActivateCode(models.Model):
    """ """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    code = models.CharField(max_length=100)
    date_expired = models.DateTimeField(default=datetime.now + timedelta(days=1))

It seem not a proper solution because datetime.now is not called but timedetla(days=1) is invoked.

How to deal with such an issue?

Upvotes: 2

Views: 72

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

In short: we can create a function to calculate the next day.

We can not add a function with a timedelta(..) object, since nor the function has an __add__ method, nor a timedelta object has a __radd__ method to add functions and timedeltas together, therefore Python/Django can not construct a new function with this syntax.

We can however solve this problem by creating a function that calculates the default time:

def tomorrow():
    return datetime.now() + timedelta(days=1)

class ActivateCode(models.Model):
    """ """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    code = models.CharField(max_length=100)
    date_expired = models.DateTimeField(default=tomorrow)

We here do not invoke the function we set as default=..., we only pass a reference to our tomorrow function, such that if Django creates a new object, it will call the tomorrow(..) function, and thus calcuate exactly the next day.

Upvotes: 2

Related Questions