1👍
✅
Override the model’s clean()
:
def clean(self):
super(Options, self).clean()
if self.question.options_set.exclude(pk=self.pk).count() > 4:
raise ValidationError("There can only be 5 Options per Question")
And for Question
accordingly. If all instances are created via the admin or some ModelForm
, this should be enough. If you create instances programmatically, you need to call clean()
in save()
:
def save(self, **kwargs):
self.clean()
super(Options, self).save(**kwargs)
You could still bulk_create
more instances, but for most cases, this should suffice.
Source:stackexchange.com