how to save objects in django with quantity validation?

1

I'm still a beginner on Django and would like to know how I would save a certain amount of students on jobs.

Example: vagas = 5 , how do I allow only 5 students to be saved?

class Turma(models.Model):  
    descricao = models.CharField(max_length=50)
    vagas = models.PositiveIntegerField()
    horario = models.CharField(max_length=5,choices=HORARIO_CHOICES,null=False,blank=False,verbose_name='Turno')
    ano = models.PositiveIntegerField(null=False,blank=False)
    semestre = models.CharField(max_length=1,choices=SEMESTRE_CHOICES,null=False,blank=False)
    aluno = models.ManyToManyField(Aluno,verbose_name='Aluno')
    professor = models.ForeignKey(Professor,verbose_name='Professor')

    def __str__(self):
        return str(self.descricao)
    
asked by anonymous 22.11.2016 / 13:55

2 answers

1

Ideally you should create a custom validator in Aluno and in that validator make a count on table Aluno checking if you already have 5 students related to that class.

    
22.11.2016 / 17:03
0

You can use Django's own validators faults. Like the MaxValueValidator , which goes

  

cast a ValidationError [...] if value is greater than max_value (translated and shortened from doc).

Your field would look something like this:

vagas = models.PositiveIntegerField(validators=[MaxValueValidator(5)])
    
24.11.2016 / 16:21