How to validate uniqueness constraint across foreign key (django)

Methods are not called on their own when saving the model.
One way to do this is to have a custom save method that calls the validate_unique method when a model is saved:

class Room(models.Model):
    zone = models.ForeignKey(Zone)
    name = models.CharField(max_length=255) 

    def validate_unique(self, exclude=None):
        qs = Room.objects.filter(name=self.name)
        if qs.filter(zone__site=self.zone__site).exists():
            raise ValidationError('Name must be unique per site')

    def save(self, *args, **kwargs):
        self.validate_unique()
    
        super(Room, self).save(*args, **kwargs)

Leave a Comment