0

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?

alias51
  • 8,178
  • 22
  • 94
  • 166
  • 2
    The datetime used for comparison in `myconstraint` is evaluated when the constraint is defined. That's why constraint is failing when you save the model from the form. What were you hoping the constraint would be? – gooberwonder Jul 28 '22 at 19:34
  • I'd like the constraint to be the less than or equal to the current system time at the start of the transaction. However the problem I have is that `django.db.models.functions.Now()` doesn't appear to be timezone aware, so I can't compare it with `my_date` which has a UTC timezone – alias51 Jul 28 '22 at 19:37
  • why not the my_date = models.DateTimeField(edi=false, auto_now_add=True) ? – Maxim Danilov Jul 28 '22 at 19:44

0 Answers0