Django models - before save/create

django, django-models

Solution

The proper location for model-level validation is in the `clean()` function. You can raise a `django.core.exceptions.ValidationError` here to describe your error. Have a look at the documentation for clean()

Problem

I have two 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 ``` The categories follow a tree like structure and I want to add products only to 'leaf categories'. When I call `my_category.products.create(...)` or similar and `my_category.is_leaf_node() == False` then it should fail. The same for `my_category.children.create(...)` if my_category has products already then it should fail. Those checks go in the save method? in a custom manager? or some where else? I would the verification to be at model level.

Original source