Let's say I have a Basket
model and I want to validate that no more than 5
Item
s can be added to it:
class Basket(models.Model):
items = models.ManyToManyField('Item')
def save(self, *args, **kwargs):
self.full_clean()
super(Basket, self).save(*args, **kwargs)
def clean(self):
super(Basket, self).clean()
if self.items.count() > 5:
raise ValidationError('This basket can't have so many items')
But when trying to save a Basket
a RuntimeError
is thrown because the maximum recursion depth is exceeded.
The error is the following:
ValueError: "<Basket: Basket>" needs to have a value for field "basket" before this many-to-many relationship can be used.
It happens in the if self.items.count() > 5:
line.
Apparently Django's intricacies simply won't allow you to validate m2m relationships when saving a model. How can I validate them then?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…