且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django unique_together 不适用于 ForeignKey=None

更新时间:2023-11-30 17:06:52

unique together 约束在数据库级别强制执行,并且您的数据库引擎似乎没有将约束应用于空值.

The unique together constraint is enforced at the database level, and it appears that your database engine does not apply the constraint for null values.

在 Django 1.2 中,您可以定义一个 clean 方法 为您的模型提供自定义验证.在您的情况下,只要父项为 None,您就需要检查具有相同名称的其他类别.

In Django 1.2, you can define a clean method for your model to provide custom validation. In your case, you need something that checks for other categories with the same name whenever the parent is None.

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 admin 编辑分类,clean 方法会被自动调用.在您自己的观点中,您必须调用 category.fullclean().

If you are editing categories through the Django admin, the clean method will be called automatically. In your own views, you must call category.fullclean().