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
                A validator is a function that takes in the fields new value, and then acts on it. They are a simple way to customize a field. They allow you to trigger functionality when a field's value changes, modify input, or limit which values are acceptable.
Django provides built-in methods to validate form data automatically. Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class.
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model .
create() will automatically save, so even if you fix your error - you will still have to make sure the arguments to create fulfill the database requirements to save a record.
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')
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With