如何从特定字段的验证器中访问正在验证的模型实例?
models.py
def question_instances(value): #validator
# not sure how to get model instance within this function
industry = model_instance.industry
questions = Question.objects.filter(industry=industry)
if questions.count() > 3:
raise ValidationError('Too many questions for this industry')
class ExampleQuestion(models.Model):
industry = models.ForeignKey(Industry, on_delete=models.CASCADE)
question = models.CharField(max_length=200, validators=[question_instances])
def __str__(self):
return self.industry.industryname
答案 0 :(得分:1)
不能。如果需要,请不要使用验证器。改用clean函数。
class ExampleQuestion(models.Model):
industry = models.ForeignKey(Industry, on_delete=models.CASCADE)
question = models.CharField(max_length=200)
def clean(self):
industry = self.industry
questions = Question.objects.filter(industry=industry).exclude(pk=self.pk)
if questions.count() > 3:
raise ValidationError('Too many questions for this industry')