ritratt
ritratt

Reputation: 1858

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?

Upvotes: 3

Views: 4932

Answers (2)

Petr Kučera
Petr Kučera

Reputation: 98

IMO this is a better solution:

class YourSerializer(serializers.Serializer)
    start = serializers.DateTimeField(required=False)
    end = serializers.DateTimeField(required=False)

    def validate(self, data):
        """
        Validation of start and end date.
        """
        start_date = data.get('start', None)
        end_date = data.get('end', None)
        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

Start and end dates should be set to required=False as neither of them is always required. Afterwards, in the validate() function, you should be getting the values using .get() function in order to prevent raising KeyError() because of a missing key.

Upvotes: 5

paras chauhan
paras chauhan

Reputation: 787

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

Upvotes: 7

Related Questions