Django constraints for UniqueConstraint does not work

101 views Asked by At

I have tried to implement constraints for UniqueConstraint for two foreign keys in the Django model. So far it has not been working as expected. Here below is the model definition :

class AssetMember(models.Model):
    asset = models.ForeignKey(Asset, null=True, related_name='assetmember_asset', on_delete=models.CASCADE)
    project = models.ForeignKey(Project, null=True, related_name='assetmember_project', on_delete=models.DO_NOTHING)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["asset", "project"], name="assetmember_unique_object")
        ]

Yet, when I try to create two assetmember objects with the same asset and project as foreign key, I can see that the constraints are not working as expected :

enter image description here

How shall I implement the model and the UniqueConstraint, so that it will not create the same object with asset and project twice?

0

There are 0 answers