How to save Django objects with quantity validation?

Asked

Viewed 258 times

2

I’m still a beginner in Django and would like to know how I would do to save a certain amount of students in vacancies.

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

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)

2 answers

1

The ideal is to create a custom validator in Aluno and in this validator make a count on the table Aluno checking if you already have 5 students related to that class.

0

You can use your own validators of Django. As the Maxvaluevalidator, who will

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

Your field would then look something like this:

vagas = models.PositiveIntegerField(validators=[MaxValueValidator(5)])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.