Which is the best way to validate mutually exclusive fields in a Django Serializer?

I Have the following serializer:

class MutuallyExclusiveSerializer(serializers.Serializer):

    field_a = serializers.Charfield()

    field_b = serializers.Charfield()

    field_c = serializers.Charfield()

I want an scalable way to raise an error if the user send more than 1 of these fields that are mutually exclusive.

I can make a custom validator but it is not easy to scale if more fields are added in the future. What is the recommended methodology in this case?

Thanks in advance!

Upvotes: 0

Views: 1131

Answers (2)

Olsi Hoxha
Olsi Hoxha

Reputation: 414

Some way I can think of is by overriding the method in which you want to make the validation, lets suppose you want to do in on create, you can do it like this:

def create(self, validated_data):
    val_len = len(validated_data)
    if val_len != 1:
        return ERROR
    return Comment(**validated_data)

Ps. By ERROR I mean that you can do whatever you want to do in that case.

Upvotes: 1

At the end, I decide to do it this way:

def validate(self, attrs):
    # Validates that only one element is added
    items = len([attr for attr in attrs.values() if attr is not None])
    if items != 1:
        raise serializers.ValidationError('Please add just 1 item at a time')

    return attrs

But if there is a better way, it would be great to know about it.

Upvotes: 1

Related Questions