1

I have the following model:

class Atividades_cumpridas(models.Model):
    id_atividade = models.ForeignKey(Atividade, on_delete=models.CASCADE)
    id_jogador = models.ForeignKey(Jogador, on_delete=models.CASCADE)
    pontos_xp_ganhos = models.IntegerField()

    def __str__(self):
        str = self.id_atividade.nome_atividade + ' - ' + self.id_jogador.nome_jogador
        return str

and i want to set the pntos_xp_ganhos max value based on Atividade.pontos_XP_maximo. How can I do that and show the max value on the admin editing page?

2 Answers 2

2

There are two ways you can do it,

  1. Using custom validators
  2. Using builtin validators

custom validators:

from django.core.exceptions import ValidationError

def validate_range(value):
    if value > Atividade.pontos_XP_maximo:
        raise ValidationError('Max value should be %s' % Atividade.pontos_XP_maximo
        )

class Atividades_cumpridas(models.Model):
        ...
        ...
        pontos_xp_ganhos = models.IntegerField(validators=[validate_range])

Using builtin validators:

MIN = 0
MAX = Atividade.pontos_XP_maximo
from django.core.validators import MinValueValidator, MaxValueValidator

class Atividades_cumpridas(models.Model):
    ...
    ...
    pontos_xp_ganhos = models.IntegerField(validators=[MinValueValidator(MIN), MaxValueValidator(MAX)]
Sign up to request clarification or add additional context in comments.

6 Comments

but for each Atividade i have a different pontos_XP_maximo
@RonaldoSilveira can please explain with example ?
For example: If i have an Atividade with id = 1, i would have, let's say, pontos_XP_maximo = 30. For the Atividade with id = 2, it would be 50.
@RonaldoSilveira is Atividade and pontos_XP_maximo are predefined >
No, Atividade is a model and pontos_XP_maximo is a field. So they are in te database and may be altered.
|
0

You can override clean() method in your model and do the validation there. As Django docs states:

This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field.

And in your case, you want to do a validation that requires access to more than a single field, which makes clean a proper method to do what you desire.

Note, however, that like Model.full_clean(), a model’s clean() method is not invoked when you call your model’s save() method.
You can see how to fix this here: Django doesn't call model clean method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.