Search code examples
djangoself-referenceself-referencing-table

Django model self-reference: prevent referencing to itself


I have the following model:

class Category(models.Model):
    name = models.CharField(max_length=255)
    parent = models.ForeignKey('self', related_name='children')

My question is that how I could prevent model to referencing itself (same object). Object should be only able to point to other categories but not to itself ('dogs' can have parent 'animals' but can't have parent 'dogs')


Solution

  • You can override the save method to throw an exception:

    def save(self, *args, **kwargs):
        if self.parent and self.parent.name == self.name:
            raise ValidationError('You can\'t have yourself as a parent!')
        return super(Category, self).save(*args, **kwargs)