Search code examples
python-3.xdjangodjango-rest-frameworkdjango-serializer

Can we make either of the serializer fields compulsory in the serializer class itself?


I have a serializer class, which I want to primarily use to fetch request data and use it to save details in different models. I want to have in request body either one or both the parameters. I can handle it in my views.py, though I want to know is there a way we can have that either or both check inside the serializer class itself?

Thanks in advance :)

#serializers.py

class ScanUpdateSerializer(serializers.Serializer):
    assets = serializers.ListField(child=serializers.DictField())
    issues = serializers.ListField(child=serializers.DictField())


Solution

  • If you want to make either of the two fields compulsory, you could use the validate method to check and enforce it.

    E.g.

    from rest_framework.exceptions import ValidationError
    
    
    class ScanUpdateSerializer(serializers.Serializer):
        assets = serializers.ListField(child=serializers.DictField())
        issues = serializers.ListField(child=serializers.DictField())
        
    
        def validate(self, attrs):
            if not ("assets" in self.initial_data or "issues" in self.initial_data):
                raise ValidationError("Either assets or issues need to be set.")
            return attrs