Search code examples
djangovalidationserializationdjango-rest-frameworkdeserialization

How to validate that at least one of two fields are present during serialization/deserialization


I am using Django Rest Framework and defining my Serializer class. The input that the Serializer class is validating contains two fields like so:

"absolute_date_range":{
  "start":...,
  "end":...,
}

"relative_date_range"="last_7"

The user can choose to pass one or both of these in. But at least one of them has to be present. If not then it should result in a validation error.

The required=True condition works only on a single field. If I do this using custom logic, which is the best place to put this logic in - the Serializer or in a Custom Field or Field level validation?

How do I enforce this in my Serializer?


Solution

  • class YourSerializer(serializers.Serializer)
        start = serializers.DateTimeField()
        finish = serializers.DateTimeField()
    
        def validate(self, data):
            """
            Validation of start and end date.
            """
            start_date = data['start']
            end_date = data['finish']
            if not start_date and not end_date:
                raise serializers.ValidationError("at least one date input required.")
            if other logic:
                other logic stuff
            return data
    

    This is better solution for you