clean() method in model and field validation

前端 未结 3 1901
挽巷
挽巷 2020-12-28 16:37

I have a problem with a model\'s clean() method and basic field validation. here\'s my model and the clean() method.

class Trial(mo         


        
3条回答
  •  情书的邮戳
    2020-12-28 17:22

    I'm struggling with a similar issue but with a ForeignKey. In your case, I would just check that the fields are not empty, and I would simplify your Boolean expressions:

    class Trial(models.Model):
    
        trial_start = DurationField()
        movement_start = DurationField()
        trial_stop = DurationField()
    
    
        def clean(self):
            from django.core.exceptions import ValidationError
            if self.trial_start:
                if self.movement_start and self.movement_start < self.trial_start:
                    raise ValidationError('movement start must be >= trial start')
                if self.trial_stop:
                    if self.trial_stop <= self.trial_start:
                        raise ValidationError('trial stop must be > trial start')
                    if self.movement_start:
                        if self.trial_stop < self.movement_start:
                            raise ValidationError('trial stop must be >= movement start')
    

提交回复
热议问题