Python – Update model fields based on POST data before saving using the Django Rest Framework

Update model fields based on POST data before saving using the Django Rest Framework… here is a solution to the problem.

Update model fields based on POST data before saving using the Django Rest Framework

I’m using the django-rest-framework and want to enrich the published data before saving it to my model, which is usually implemented using the model’s clean method, as shown in the example in the django documentation:

class Article(models. Model):
...
def clean(self):
    # Don't allow draft entries to have a pub_date.
    if self.status == 'draft' and self.pub_date is not None:
        raise ValidationError(_('Draft entries may not have a publication date.'))
    # Set the pub_date for published items if it hasn't been set already.
    if self.status == 'published' and self.pub_date is None:
        self.pub_date = datetime.date.today()

Unfortunately, the

django-rest-framework serializer doesn’t call the model’s clean method like a standard django Form does, so how do I do that?

Solution

From the official docs :

The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm. Use the serializer .validate() method to perform a final validation step on incoming data where required.

There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate(). You can do so by explicitly instantiating a model instance in the .validate() method.

def validate(self, attrs):
    instance = ExampleModel(**attrs)
    instance.clean()
    return attrs

Related Problems and Solutions