gpt4 book ai didi

Django 模型 - 在保存/创建之前

转载 作者:行者123 更新时间:2023-12-04 02:58:56 24 4
gpt4 key购买 nike

我有两个模型:

class Category(MPTTModel):
name = models.CharField(max_length=50,unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
def __unicode__(self):
return self.name

class Product(models.Model):
name = models.CharField(max_length=50)
categories = models.ManyToManyField(Category,related_name='products')
def __unicode__(self):
return self.name

类别遵循树状结构,我只想将产品添加到“叶类别”。
当我调用 my_category.products.create(...) 或类似函数并且 my_category.is_leaf_node() == False 时,它应该会失败。
my_category.children.create(...) 如果 my_category 已经有产品,那么它应该会失败。
那些支票进入保存方法?在自定义管理器中?或者别的地方?我希望在模型级别进行验证。

最佳答案

模型级验证的正确位置是在 clean() 函数中。您可以在此处引发 django.core.exceptions.ValidationError 来描述您的错误。看看the documentation for clean()

关于Django 模型 - 在保存/创建之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15575535/

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