python-3.xdjangodjango-modelsdjango-constraints

use db constraints to limit a foreign key to have only one boolean value false while others true


when i run migrations i get an error could not create unique index "unique_is_performed_False" DETAIL:  Key (is_performed)=(f) is duplicated.i am having a model below

class MaintenancePersonnel(models.Model):
    performed_by=models.ForeignKey(User,on_delete=models.CASCADE)
    work_performed=models.ForeignKey(EquipmentMaintenanceSchedule,on_delete=models.CASCADE)
    comments=models.TextField(blank=True,null=True)
    is_performed=models.BooleanField(default=False)

I want for a given work performed to have only one field that has is_performed False

i have tried using condition but this seems to force only one model to have is_performed equal to false regardless of the work performed

class Meta:
        constraints = [
        models.UniqueConstraint(fields=['work_performed','is_performed'], condition=models.Q(is_performed=False), name='unique_is_performed_False')
    ]

Solution

  • Try setting your UniqueConstraint field to just work_performed with the is_performed condition.

    models.UniqueConstraint(fields=['work_performed'], condition=models.Q(is_performed=False), name='unique_is_performed_False')
    

    This should limit your models to one work_performed where is_performed is false. It seems similar to the case provided in the docs