我看到一些ppl在我面前有这个问题,但是在旧版本的Django上,我运行的是1.2.1。

我有一个看起来像的模型:

class Category(models.Model):
 objects = CategoryManager()

 name = models.CharField(max_length=30, blank=False, null=False)
 parent = models.ForeignKey('self', null=True, blank=True, help_text=_('The direct parent category.'))

 class Meta:
  unique_together = ('name', 'parent')

每当我尝试在管理员中保存一个父级设置为“无”的类别时,当存在另一个具有“相同”名称且父级设置为“无”的类别时,它仍然可以工作。

关于如何优雅解决此问题的想法?

最佳答案

唯一在一起约束是在数据库级别强制执行的,并且看来您的数据库引擎未将约束应用于空值。

在Django 1.2中,您可以为模型定义clean method以提供自定义验证。对于您的情况,只要父级为“无”,您就需要检查同名的其他类别的内容。

class Category(models.Model):
    ...
    def clean(self):
        """
        Checks that we do not create multiple categories with
        no parent and the same name.
        """
        from django.core.exceptions import ValidationError
        if self.parent is None and Category.objects.filter(name=self.name, parent=None).exists():
            raise ValidationError("Another Category with name=%s and no parent already exists" % self.name)

如果您是通过Django管理员编辑类别,则clean方法将自动被调用。在您自己的 View 中,您必须调用category.fullclean()

关于Django unique_together不适用于ForeignKey = None,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3488264/

10-15 23:23