Django模型 - 保存/创建之前

时间:2013-03-22 16:38:55

标签: django django-models

我有两个型号:

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已经有产品,则my_category.children.create(...)也是如此,那么它应该会失败 这些检查是否采用保存方法?在自定义经理?或者别的地方?我的验证是在模型级别。

1 个答案:

答案 0 :(得分:4)

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

相关问题