Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models - before save/create

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.

like image 671
olanod Avatar asked May 08 '26 15:05

olanod


1 Answers

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()

like image 130
minism Avatar answered May 11 '26 06:05

minism