akhavro
akhavro

Reputation: 101

Same validator for different fields

So this is the situation:

I have two serializer classes, one inheriting from another.

class FatherSerializer(...):
    class Meta(object):
        model = Person
        fields = ('name', 'email', 'brother')

    name = serializers.CharField()
    email = serializers.EmailField()
    brother = serializers.CharField()

    def validate_email(self, value):
        if Person.objects.filter(email=value).exists():
            raise serializers.ValidationError('Such email already exists')
        return value

    def validate_brother(self, value):
        if not Person.objects.filter(name=value).exists():
            raise serializers.ValidationError('Such person doesnt exist')
        return Person.objects.get(name=value)

class ChildSerializer(FatherSerializer):
    class Meta(object):
        model = Person
        fields = ('name', 'email', 'sister')

    sister = serializers.CharField()

I want to use the same validator for "sister" as it is used for "brother". It works for the email, since the name of the field is the same. But is there a way of making the same serializer to work for 2 different fields?

I tried a custom validator, by implementing it outside of both classes and using it in validators parameter of the Field. But it is not working properly, because I want the returned value to be a Person object, but all I get is the original input value (so, "name").

Thank you in advance.

Upvotes: 0

Views: 45

Answers (2)

henriquesalvaro
henriquesalvaro

Reputation: 1272

You can declare your own SiblingField with your custom validation and then use it both on your FatherSerializer for brother and on your ChildSerializer for sister.

class SiblingField(serializers.CharField):
    <add your custom validation methods here>

class FatherSerializer(...):
    brother = SiblingField()

class ChildSerializer(FatherSerializer):
    sister = SiblingField()

Upvotes: 1

Tarjeet Singh
Tarjeet Singh

Reputation: 132

You can use FatherSerializer there for 'sister' field

sister = FatherSerializer()

Upvotes: 1

Related Questions