I have a timezone aware model field with a CheckConstraint:
class MyModel(models.Model):
my_text = models.CharField()
my_date = models.DateTimeField()
class Meta:
constraints = [ models.CheckConstraint(
check=Q(my_date__lte=django.utils.timezone.now()),
name='mycontraint' ]
In my form I process the data to add my_date manually:
def form_valid(self, form):
obj = form.save(commit=False)
obj.my_date = timezone.now()
obj.save()
When I save this model I get new row for relation "mymodel_mydate" violates check constraint 'myconstraint'.
I know the reason it's failing is that the datetime for my_date
is greater than timezone.now()
in the checkconstraint, but why is this? Is timezone.now()
in the checkconstraint somehow cached earlier?
I can see the value for my_date in the debug failing row (which is correct, in UTC+00 and matches my system time as I expect), however I don't know how to compare this to the timezone value in the CheckConstraint?