Django doesn't call model clean method

前端 未结 4 1119
后悔当初
后悔当初 2020-12-29 03:00

I have a view, which creates models from CSV file. I\'ve added clean method to the model class definition, but it isn\'t called when model is created.

Here is exampl

相关标签:
4条回答
  • 2020-12-29 03:16

    Apparently model.clean() is never called to ensure backward compatibility. For more information on this: https://code.djangoproject.com/ticket/13100

    0 讨论(0)
  • 2020-12-29 03:16

    Apparently in newer versions of Django the ModelForm.full_clean does call it's instance's full_clean method:

    • https://github.com/django/django/blob/14e2b1/django/forms/models.py#L403
    0 讨论(0)
  • 2020-12-29 03:19

    To call the model clean method we will override save method. Check the link: https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.clean

    class CommonMeasurement(models.Model):
        timestamp = models.DateTimeField()
        value = models.FloatField()
        run = models.ForeignKey(Run)
    
        def clean(self):
            if self.timestamp < self.run.timestamp_start or self.timestamp > self.run.timestamp_end:
                raise django_excetions.ValidationError('Measurement is outside the run')
    
        def save(self, *args, **kwargs):
            self.full_clean()
            return super(CommonMeasurement, self).save(*args, **kwargs)
    
    0 讨论(0)
  • 2020-12-29 03:19

    I've found a solution to override method:

    class CommonMeasurement(models.Model):
        timestamp = models.DateTimeField()
        value = models.FloatField()
        run = models.ForeignKey(Run)
    
        objects = models.Manager()
        analyzes = managers.MeasureStatManager()
    
        def save(self, **kwargs):
            self.clean()
            return super(CommonMeasurement, self).save(**kwargs)
    
        def clean(self):
            super(CommonMeasurement, self).clean()
            print 'here we go'
            if self.timestamp < self.run.timestamp_start or self.timestamp > self.run.timestamp_end:
                raise django_excetions.ValidationError('Measurement is outside the run')
    

    But I'm not sure that it can be a good decision.

    0 讨论(0)
提交回复
热议问题