gpt4 book ai didi

Django unique_together 不适用于 ForeignKey=None

转载 作者:行者123 更新时间:2023-12-04 05:34:49 26 4
gpt4 key购买 nike

我看到一些人在我之前遇到过这个问题,但是在旧版本的 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')

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

关于如何优雅地解决这个问题的想法?

最佳答案

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

在 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 方法。在你自己看来,你必须调用 category.fullclean() .

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com