Saving foreign key ID with Django REST framework serializer

django rest framework

If you are using Django REST framework on serving your APIs, you probably did the below

code in returning the related object in your serializer.

class MyTableSerializer(serializers.ModelSerializer):
    user = UserSerializer(many=False, read_only=True)

    class Meta:
        fields = '__all__'
        model = MyTable

But doing this will not allow your API to pass the foreign key id. Instead, you need to include the field name in the serializer like the code below:

class MyTableSerializer(serializers.ModelSerializer):
    user = UserSerializer(many=False, read_only=True)
    user_id = serializers.IntegerField(write_only=True)

    class Meta:
        fields = '__all__'
        model = MyTable

 

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.