multiple constraints not working in the db

22 views
Skip to first unread message

mccc

unread,
Apr 3, 2020, 1:46:40 PM4/3/20
to Django users
Hello,

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.

mccc

unread,
Apr 3, 2020, 1:48:20 PM4/3/20
to Django users
oh, forgot: versions are Python 3.7.6 and Django 2.2.11
Reply all
Reply to author
Forward
0 new messages