请参阅下面的代码。基本上,当用户创建这个类的对象时,他们需要指定value_type
。如果value_type==2
(百分比),然后percentage_calculated_on
(这是一个CheckboxSelectMultiple在表单/模板端需要有一个或多个项目检查。模型验证不允许我像我试图验证 - 它基本上抛出一个例外,它告诉我,在使用多对多关系之前,实例需要有一个主键值,但是我需要在保存之前先验证对象,我已经在form(modelform)一侧(使用形式的清洁方法),但同样的事情发生也有。django manytomany验证
如何去实现这个验证?
INHERENT_TYPE_CHOICES = ((1, 'Payable'), (2, 'Deductible'))
VALUE_TYPE_CHOICES = ((1, 'Amount'), (2, 'Percentage'))
class Payable(models.Model):
name = models.CharField()
short_name = models.CharField()
inherent_type = models.PositiveSmallIntegerField(choices=INHERENT_TYPE_CHOICES)
value = models.DecimalField(max_digits=12,decimal_places=2)
value_type = models.PositiveSmallIntegerField(choices=VALUE_TYPE_CHOICES)
percentage_calculated_on = models.ManyToManyField('self', symmetrical=False)
def clean(self):
from django.core.exceptions import ValidationError
if self.value_type == 2 and not self.percentage_calculated_on:
raise ValidationError("If this is a percentage, please specify on what payables/deductibles this percentage should be calculated on.")
我已将Manoj Govindan的答案标记为“接受”,因为它解决了问题。不过,我仍然希望使用Django的模型验证进行验证。所以如果有人有任何想法,请尽力在此发布。谢谢。 – chefsmart 2010-10-04 12:53:43
同样的问题:http://stackoverflow.com/questions/7986510/django-manytomany-model-validation – user920391 2013-02-08 16:02:59