I’d like to use this constraint on my Django model:
models.UniqueConstraint(
fields=["edificio", "studio"],
condition=models.Q(attiva=True),
name="unique_attiva_per_edificio_studio",
violation_error_message=_(
"cannot have two active configurations for the same studio",
),
)
But since I’m on MariaDB (and I cannot change it) conditional constraints/indexes aren’t supported yet. So I’m extending the validate_constraints
function in my EdificioConfigurazione
model to check it.
def validate_constraints(self, exclude=None):
super().validate_constraints(exclude)
# TODO: this will be removed once MySQL/MariaDB supports conditional constraints
manager = EdificioConfigurazione.objects
multiple_attiva_per_edificio = (
manager.values("edificio", "studio")
.annotate(
rcount=models.Count("id", filter=models.F("attiva")),
)
.filter(rcount__gt=1)
)
if multiple_attiva_per_edificio.exists():
violation_error_message = _(
"cannot have two active configurations for the same studio",
)
raise ValidationError(violation_error_message)
Assuming this is the right approach to do this (I’m open to suggestions), I cannot enforce this check since the instance to be added/modified (which is self
) is not committed to the DB yet. How can I use the instance? My idea would be looking at the self.pk
field and:
- if
self.pk is None
: I add the instance to the queryset before the checks - else: the instance is already in the DB (I’m modifying it for example) so I need to update the queryset to use it instead of the one committed.
Once again, I don’t know if extending validate_constraints
is the right approach but how would I implement this logic?