0

When I try to add a constraint on closed_at field, I got a migration error django.db.utils.ProgrammingError: functions in index predicate must be marked IMMUTABLE. Is it any possible way to do it?

from django.db.models.functions import Now

class ModelName():
    # Other fields 
    closed_at = models.DateTimeField()

    class Meta:
    
        constraints = [
            models.UniqueConstraint(
                fields=['field_1'],
                condition=Q(closed_at__gt=Now()),
                name='unique_field_1_constraint',
            ), 
        ]


Migration:


class Migration(migrations.Migration):

    dependencies = [
        ('_____', '__________'),
    ]

    operations = [

        migrations.AddConstraint(
            model_name='model_name',
            constraint=models.UniqueConstraint(condition=models.Q(
                ('closed_at__gt', django.db.models.functions.datetime.Now())
            ), fields=('field_1',), name='unique_field_1_constraint'),
        ),
    ]

Blend
  • 1
  • 1
  • 2
    NOW() is not immutable, it changes every nanosecond. The condition is just not right you need to leave it out or use something that makes sense, like NOT NULL – Frank Heikens Oct 06 '22 at 09:22
  • For database integrity I need to have this constraint and the field cannot be null. I was looking for a possible solution but couldn't find so far. – Blend Oct 06 '22 at 09:26
  • Then use NOT NULL in the constraint when you have not null condition. – Frank Heikens Oct 06 '22 at 09:31
  • Not a constraint based solution, but perhaps a viable one could be a field validator? E.g. something similar to https://stackoverflow.com/a/68117097/4183498 (not tested). – Dušan Maďar Oct 06 '22 at 09:48

0 Answers0