Django 模型自引用:防止引用自身
Django model self-reference: prevent referencing to itself
我有以下型号:
class Category(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', related_name='children')
我的问题是如何防止模型引用自身(同一对象)。对象应该只能指向其他类别而不能指向自身('dogs' 可以有父级 'animals' 但不能有父级 'dogs')
您可以覆盖 save
方法以抛出异常:
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)
对于UI,可以限制使用limit_choices_to
:https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to
我有以下型号:
class Category(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', related_name='children')
我的问题是如何防止模型引用自身(同一对象)。对象应该只能指向其他类别而不能指向自身('dogs' 可以有父级 'animals' 但不能有父级 'dogs')
您可以覆盖 save
方法以抛出异常:
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)
对于UI,可以限制使用limit_choices_to
:https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to