How can I create a complex Django model validation for Django Admin?

I have the following model in Django:

class Bout (models.Model):
    fighter_1 = models.ForeignKey(Fighter, related_name="bout_fighter_1")
    fighter_2 = models.ForeignKey(Fighter, related_name="bout_fighter_2")
    winner = models.ForeignKey(Fighter, related_name="bout_winner", 
        blank=True, null=True, help_text='Leave blank for draw.') 
    date = models.DateField()
    cancelled = models.BooleanField()

I would like the “idiot-proof” administration for my notes. On the contrary, I want to create three rules:

  • Fighter 1 is not the same as fighter 2 (which is only suitable for the monty python skeet).

  • The winner must be in a battle (for example, either Fighter 1 or Fighter 2)

  • The winner cannot be determined before the match. (After all, this is not WWE.)

All three rules require checking one field for another field in the same record. Is it possible to do this in django, either using native django methods, or resorting to using python?

+4
2

: Django, " django". , " Django"; , API Django.

. Bout , , , . , :

class BoutForm(forms.ModelForm):
    class Meta:
        model = Bout

    def clean(self):
        fighter_1 = self.cleaned_data.get('fighter_1')
        fighter_2 = self.cleaned_data.get('fighter_2')
        winner = self.cleaned_data.get('winner')  
        date = self.cleaned_data.get('date')

        if not (fighter_1 and fighter_2 and (fighter_1.id != fighter_2)):
            raise forms.ValidationError("Both fighters cannot be the same")

        if not (winner and (winner.id == fighter_1.id or winner.id == fighter_2.id)):
            raise forms.ValidationError("Winner is not in the fight")

        if not (date and date < datetime.today()):
            raise forms.ValidationError("Winner is not in the fight")

        return self.cleaned_data

. . Django, fangled .

, , API (, Bout ), , save() Bout .

+1

Manoj Govindan , ... , - :

def clean(self):
    if self.fighter_1 == self.fighter_2:
        raise ValidationError('Fighter 1 can not be Fighter 2.')
    if (self.winner != self.fighter_1) and (self.winner != self.fighter_2):
        raise ValidationError('Winner must be in the bout.')
    if (self.date >= datetime.date.today()) and (self.winner):
        raise ValidationError('Winner can not be set before match.')
0

All Articles