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

 

Comments

person

Phillip (not verified)

9 months ago Permalink

This has saved me alot of pain. Thank you

person

Somangshu (not verified)

4 months ago Permalink

You saved the day, Simple to implement and understand, Although the create method had to be updated. Thanks again

person

Mohammad (not verified)

4 months ago Permalink

Thank you you very much. I had been searching for this for two days

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.