Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing model instance from validator

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
like image 948
Jason Howard Avatar asked Mar 09 '19 20:03

Jason Howard


People also ask

What does validators do in the code field validators?

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.

How does Django validate data?

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.

What is Django instance model?

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 .

Does create call save Django?

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.


1 Answers

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')
like image 166
Daniel Roseman Avatar answered Oct 20 '22 13:10

Daniel Roseman