10

How would I access the instance of the model that is being validated from within the validator for a specific field?

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
Jason Howard
  • 1,464
  • 1
  • 14
  • 43
  • Why do you think you need this? The `value` parameter contains the value for industry. – Daniel Roseman Mar 09 '19 at 20:34
  • Hi Daniel, Good to talk to you again. After I posted my question, I realized this. I moved the validator to the industry line in the model. However, within the validator, I now need to get the model instance so that I can check to see if I'm creating a new model or editing an existing one. That will dictate if I use > 3 or > 4 as the condition. Thanks Daniel – Jason Howard Mar 09 '19 at 20:41

1 Answers1

12

You can't. If you need this, don't use a validator; use a clean function instead.

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')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895