gregdevs
gregdevs

Reputation: 713

Django Rest Framework - Posting to writable nested field containing a Foreign Key value

New to DRF and so far it's been very useful, as is the documentation..however I'm trying to wrap my head around how this should work. I'm basically trying to, on POST create a new reputation object that has a foreignkey related field mentionid. mentionid already exists.

The reputation object is represented correctly, and looks like:

{
    "id": 5,
    "author": 1,
    "authorname": "name",
    "value": 100,
    "mentionid": {
        "id": 1,
        "author": 1,
        "somekey": "some value"
    }

}

but when I Post I receive this error:

The `.create()` method does not support writable nestedfields by default. Write an explicit `.create()` method for serializer `quickstart.serializers.ReputationSerializer`, or set `read_only=True` on nested serializer fields.

I'm assuming I need to define a create method in the serializer, but out of curiosity I noticed if I comment out the line referencing the MentionSerializer I can successfully post the mentionid field, but it returns an object with just the mentionid foreign key value, which is not what I want. So I'm curious if I'm missing a parameter in my model that would solve my issue. Maybe i need to set a default value on the Foreign Key in my model? thanks for any insight.

{
    "id": 5,
    "author": 1,
    "authorname": "name",
    "value": 100,
    "mentionid": 1

}

my Model has a Reputation class:

class Reputation(models.Model):
    mentionid = models.ForeignKey(Mention)

I have a serializer:

class ReputationSerializer(serializers.ModelSerializer):
    mentionid = MentionSerializer()
    class Meta:
        model = Reputation
        fields = ('id', 'author',  'authorname', 'value', 'mentionid')  

Upvotes: 1

Views: 1128

Answers (1)

gregdevs
gregdevs

Reputation: 713

So I came up with a solution using PrimaryKeyRelatedField

The idea here is to have a field child_id that is write-only which accepts a value which sets the mentionid source

class ReputationSerializer(serializers.ModelSerializer):
    mentionid = MentionSerializer()
    child_id = serializers.PrimaryKeyRelatedField(queryset=Mention.objects.all(), source='mentionid', write_only=True)

    class Meta:
        model = Reputation
        fields = ('id', 'author',  'authorname', 'value', 'mentionid', 'child_id', 'created_date', 'published_date')

Upvotes: 1

Related Questions