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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With