[Answered ]-Django check-contraint boolean expression [postgresql]

1👍

Adding an is_default=False case get you closer to your conditions.

I tested with Django==3.1.4 and the OR method resulted in this constraint:

"default_role_check" CHECK (color::text = '#969696'::text AND is_default AND name::text = '@everyone'::text AND "position" = 1 OR NOT is_default)

Constraint example:

class Role(BaseModel):

    class Meta:
        verbose_name = 'role'
        verbose_name_plural = 'roles'
        ordering = ['position', 'cluster']
        required_db_features = {
            'supports_deferrable_unique_constraints',
        }
       constraints = [
            models.UniqueConstraint(
                fields=['position', 'cluster'],
                name='deferrable_unique_role_position',
                deferrable=models.Deferrable.DEFERRED
            ),
            models.CheckConstraint(
                name='default_role_check',
                check=(models.Q(
                    is_default=True,
                    position=1,
                    color='#969696',
                    name='@everyone'
                ) |
                    models.Q(
                    is_default=False,
                )
                )
            )
        ]
    permission_flags = [
        'READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS', 'MANAGE_ROLES',
        'MANAGE_CLUSTER', 'MANAGE_DATASHEETS', 'MANAGE_FIELDS', 'MANAGE_CONSTRAINTS',
        'KICK_MEMBERS', 'MANAGE_MEMBERS',
    ]

    default_perm_flags = ['READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS']

    def __str__(self):
        return self.name

    objects = managers.RolesManager()
    positions = managers.PositionalManager()
    permissions = BitField(flags=permission_flags, default=default_perm_flags, db_index=True)
    position = models.PositiveSmallIntegerField(null=True, blank=True, db_index=True, editable=True)
    name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True, default='new role')
    color = ColorField(db_index=True, default='#969696')
    is_default = models.BooleanField(default=False, db_index=True)
    cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE, editable=False)

Leave a comment