'How can I add the next 1st of August as DateTimeField default value in Django?
I have the following model and want to add the next August (midnight time) from now as a default value for offer_start:
class Offer(models.Model):
"""
A table to store all available offers for an upcoming season
"""
club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='offer')
season_start = models.CharField(max_length=40)
seasons_duration = models.IntegerField()
offer_start = models.DateTimeField(auto_now_add=False, default= ???)
roi_goal = models.FloatField()
roi_point = models.FloatField()
def __str__(self):
return f'Offer by {self.club} for season {self.season_start}'
Is there any way to make such a specification?
Solution 1:[1]
Yes, you can make a callable with:
from django.utils.timezone import now
def next_august_1():
today = now().date()
if (today.month, today.day) >= (8, 1):
return datetime(today.year+1, 8, 1)
return datetime(today.year, 8, 1)
and then pass the callable to the DateTimeField:
class Offer(models.Model):
# …
# without parenthesis ?
offer_start = models.DateTimeField(default=next_august_1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
