[Django]-Model datetime field validation for fields with auto_now

6👍

Django REST framework used to call Model.clean, which was previously the recommended place for putting validation logic that needed to be used in Django forms and DRF serializers. As of DRF 3.0, this is no longer the case and Model.clean will no longer be called during the validation cycle. With that change, there are now two possible places to put in custom validation logic that works on multiple fields.

If you are only using Django REST framework for validation, and you don’t have any other areas where data needs to be manually validated (like a ModelForm, or in the Django admin), then you should look into Django REST framework’s validation framework.

class MySerializer(serializers.ModelSerializer):
    # ...

    def validate(self, data):
        # The keys can be missing in partial updates
        if "expirydate" in data and "createdon" in data:
            if data["expirydate"] < data["createdon"]:
                raise serializers.ValidationError({
                    "expirydata": "Expiry date cannot be greater than created date",
                })

        return super(MySerializer, self).validate(data)

If you need to use Django REST framework in combination with a Django component that uses model-level validation (like the Django admin), you have two options.

  1. Duplicate your logic in both Model.clean and Serializer.validate, violating the DRY principle and opening yourself up to future issues.
  2. Do your validation in Model.save and hope that nothing strange happens later.

but I dont know if this would be a good idea, since now I am raising an error which the programmer may forget to catch.

I would venture to say that it would be better for the error to be raised than for the saved data to possibly become invalid on purpose. Once you start allowing invalid data, you have to put in checks anywhere the data is used to fix it. If you don’t allow it to go into an invalid state, you don’t run into that issue.

I am also not sure if the fields would be populated when this method would run.

You should be able to assume that if an object is going to be saved, the fields have already been populated with their values.

2👍

If you would like to both Model Validation and Serializer validation using Django REST Framework 3.0, you can force your serializer to use the Model validation like this (so you don’t repeat yourself):

import rest_framework, django
from rest_framework import serializers

class MySerializer(serializers.ModelSerializer):
    def validate(self, data):
        for key, val in data.iteritems():
            setattr(self.instance, key, val)
        try:
            self.instance.clean()
        except django.core.exceptions.ValidationError as e:
            raise rest_framework.exceptions.ValidationError(e.message_dict)

        return data

I thought about generating a new function from my model’s clean() function’s code, and have it either spit out django.core.exceptions.ValidationError or rest_framework.exceptions.ValidationError, based on a parameter source (or something) to the function. Then I would call it from the model, and from the serializer. But that hardly seemed better to me.

0👍

If you want to make sure that your data is valid on the lowest level, use Model Validation (it should be run by the serializer class as well as by (model)form classes (eg. admin)).

If you want the validation to happen only in your API/forms put it in a serializer/form class. So the best place to put your validation should be Model.clean().

Validation should never actually happen in views, as they shouldn’t get too bloated and the real business logic should be encapsulated in either models or forms.

Leave a comment