'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 1:[1]
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)
Solution 2:[2]
For UI one can restrict using limit_choices_to
: https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | bhdnx |