嘿,我有问题与类别的父。正如你在代码中看到的,我有一个外键指向它自己的类别。现在我不希望category的实例是它自己的子实例。到目前为止,我已经尝试了unique_together和UniqueConstraint,但没有工作。
class Category(models.Model):
parent = models.ForeignKey('self', related_name="children", on_delete=models.CASCADE, blank=True, null=True) #'self' to indicate a self-reference.
title = models.CharField(max_length=100)
slug = AutoSlugField(populate_from='title', unique=True, null=False, editable=True)
logo = models.ImageField(upload_to="catlogo", blank=True, null=True, help_text='Optional')
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
#enforcing that there can not be two categories under a parent with same slug
verbose_name_plural = "categories"
constraints = [
models.UniqueConstraint(fields=['slug', 'parent'], name='unique_parent')
]
您可以自己为它添加一些验证,您应该简单地覆盖validate_unique方法并将此验证添加到其中。试试这个。
class Category(models.Model):
parent = models.ForeignKey('self', related_name="children", on_delete=models.CASCADE, blank=True, null=True) #'self' to indicate a self-reference.
title = models.CharField(max_length=100)
slug = AutoSlugField(populate_from='title', unique=True, null=False, editable=True)
logo = models.ImageField(upload_to="catlogo", blank=True, null=True, help_text='Optional')
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "categories"
def validate_unique(self, *args, **kwargs):
super(Category, self).validate_unique(*args, **kwargs)
if self.__class__.objects.
filter(parent=self.parent, slug=self.slug).
exists():
raise ValidationError(
message='Category with this (parent, slug) already exists.',
code='unique_together',
)