Truly dynamic DateField values in Django
Some of my app models define date ranges (e.g. of contracts), where the current instance has no fixed end date (i.e. it should always evaluate to today). Setting the default
parameter on the end
field –
class Contract(models.Model):
building = models.ForeignKey(Building, on_delete=models.CASCADE)
service = models.ForeignKey(Service, on_delete=models.CASCADE)
begin = models.DateField()
end = models.DateField(default=datetime.date.today)
– will populate the field with a fixed value. A property to work around the problem –
class Contract(models.Model):
building = models.ForeignKey(Building, on_delete=models.CASCADE)
service = models.ForeignKey(Service, on_delete=models.CASCADE)
begin = models.DateField()
end = models.DateField(blank=True)
@property
def get_end(self):
if not self.end:
return datetime.date.today()
return self.end
– does not work with querysets. Is there any way to implement a truly dynamic value on the database level using Django's ORM?
The best options available for a sudo-dynamic DateField
are auto_now
and auto_now_add
as mentioned in the comments. The former updates the DateField on each .save()
call and the latter does it at creation (Django doc).
The other option, as mentioned by Adrian, is to set the end
as Null
and use a conditional query for your claen()
function. You can do that either by introducing an if statement or by using Case()
and When()
. You can check this Django doc or see this answer for more information.
There are other options for having a dynamic date in your model but not as a DateField
, which I assume is not what you are looking for nor anything near a 'clean code'.