Mukund Gandlur
Mukund Gandlur

Reputation: 869

Validating a foreign key field in a serializer django rest framework

I am using django rest framework and have a html form which sends data to the rest api. I am doing a serializer.is_valid check and save() on the request data. In the the front end form I have an ID field which is a foreign key in the serializer's model. And when serializer.is_valid is run, it throws an error that says the foreign key object is missing. To overcome this I am trying to get the Foreign key object instance using the id from the input html form and insert it in the serializer data.

I have written a definition validate_ in my serializer and I am assuming it to run(as per this tutorial - http://www.django-rest-framework.org/api-guide/serializers/#validation) when serializer.is_valid() is executed. But this definition is not being executed. Appreciate help.

class TeamViewSet(viewsets.ModelViewSet):
    serializer_class = TeamSerializer
    queryset = Team.objects.all()
    def create(self, request, *args, **kwargs):

        permission_classes = (
            permissions.IsAuthenticated
        )
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid()


        return Response(.....)

Serializer

class TeamSerializer(serializers.ModelSerializer):

    class Meta:
        model = Team
        fields = ('id','name','description','leader')

    def validate_leader(self, leader_id):
        try:
            data = Leaders.objects.get(id=leader_id)
        except Exception as e:
            raise ValidationError(....)
        return data

Upvotes: 2

Views: 6917

Answers (1)

Mukund Gandlur
Mukund Gandlur

Reputation: 869

I get it now. The validate method doesn't get executed if the field is not included in the request data. After I have included the field in the request data, the validate method for that field is running.

Upvotes: 2

Related Questions