Friday, October 4, 2024

Postgres failure when trying to remove check constraint

Hi, everyone.

I have the following db model:

class Template(models.Model):
    max_documents = models.PositiveIntegerField(default=1)
    is_comparison = models.BooleanField(default=False)
    ...
    class Meta:
        constraints = [
            models.CheckConstraint(
                check=models.Q(is_comparison=False) | models.Q(max_documents__gte=2, is_comparison=True),
                name="is_comparison_requires_min_documents",
            ),
        ]

I recently added this check constraint above and makemigrations created the following db migration: 

class Migration(migrations.Migration):
    dependencies = [
        ...
    ]

    operations = [
        migrations.AddConstraint(
            model_name="template",
            constraint=models.CheckConstraint(
                check=models.Q(
                    ("is_comparison", False),
                    models.Q(("is_comparison", True), ("max_documents__gte", 2)),
                    _connector="OR",
                ),
                name="is_comparison_requires_min_documents",
            ),
        ),
    ]

Today I deleted the constraint and ran makemigrations again, which created this second migration:

class Migration(migrations.Migration):
    dependencies = [
        ...
    ]

    operations = [
        migrations.RemoveConstraint(
            model_name="template",
            name="is_comparison_requires_min_documents",
        ),
    ]

When I try to run the 2nd migration, I get the following Postgres error from Django:
django.db.utils.ProgrammingError: constraint "is_comparison_requires_min_documents" of relation "ai_template" does not exist

I checked the ai_template table schema and confirmed there is no check constraint there. It seems to me Django didn't create the check constraint on the Postgres db side (maybe it was enforcing it on its side) and now is trying to remove it from Postgres. Is that a bug or am I missing something?

Thanks in advance!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8d16410d-ded2-4f2f-a457-675127825443n%40googlegroups.com.

No comments:

Post a Comment