I've got these models:
class Container(models.Model):
...
class Meta:
constraints = [
models.CheckConstraint(
check=~Q(elements=None),
name='container_must_have_elements'
),
]
class Element(models.Model):
container = models.ForeignKey(Container),
related_name='elements',
on_delete=models.CASCADE
)
I want to enforce the constraint that every Container
object must have at least one Element
referencing it via the foreign key relation.
As you can see I already added a check constraint. However, the negation operator ~
on the Q
object seems to be forbidden. I get django.db.utils.NotSupportedError: cannot use subquery in check constraint
when I try to apply the generated migration.
Without the negation operator the constraint seems to be valid (it only fails due to a data integrity error).
Is there another way I can express this constraint so it is supported by CheckConstraint
?
(E.g. is there a way to check if the set of elements
is not empty?)
Container
without elements but in order to create anElement
you need a container to reference. It seems to me that it makes no sense to have this constraint – MarriageCheckConstraint
in your model but set it in your migration usingRunSQL
– Doble