0

I'm having issues getting multiple constraints to work (in postgres, if it matters). Here is the Meta:

class Meta:
    constraints = [
        CheckConstraint(
            check=(Q(target_value__gt=0) & ~Q(target_metric=DEFAULT)) |
                  (Q(enabled=False) |
                   Q(status=IMPORTING) |
                   Q(status=IMPORT_FAILURE)),
            name="positive_target_value",
        )
    ]

It would seem straightforward enough to me, but it ends up not working. Here is the generated SQL (pulled from the db itself):

target_value > 0.0::double precision AND NOT target_metric::text = 'DEFAULT'::text OR enabled = false OR status = 20 OR status = 30

And here is proof that it should actually work (pulled from a django console, where the conditions are copied from the migration file):

Folder.objects.filter(models.Q(models.Q(('target_value__gt', 0), models.Q(_negated=True, target_metric='DEFAULT')), ('enabled', False), ('status', 20), ('status', 30), _connector='OR'))
web_1       | Out[5]: <QuerySet [<Folder: aDifferentFolder>]>

Folder.objects.filter(models.Q(models.Q(('target_value__gt', 0), models.Q(_negated=True, target_metric='**SOMETHING DIFFERENT**')), ('enabled', False), ('status', 20), ('status', 30), _connector='OR'))
web_1       | Out[7]: <QuerySet [< Folder: Folder aDifferentFolder >, < Folder: Folder thisFolderShouldNotHaveBeenCreted>]>

Anybody has any suggestion? Btw, I also tried switching the first condition with the second one, effectively putting the AND at the bottom of the query, but it didn't seem to have any effect.

Thanks a lot.

1 Answer 1

1

The culprit was that postgres returns true on constraint also if the value is null, so now I know.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.