[Answered ]-How to update PrimaryKeyRelatedField field of a nested relation? / Allow to GET a full object but POST/PUT/PATCH with only an id on related fields

1๐Ÿ‘

โœ…

I tried changing the following line of code

address_instance.country_id = address['country_id']

to

address_instance.country = address['country']

and it works, When I send country_id updates the correct id, but it is necessary to have country_id declared

country = CountrySerializer(read_only = True)
country_id = serializers.PrimaryKeyRelatedField(source="country", queryset = Country.objects.all())

in JSON Request

...
"country_id": 3,
...
๐Ÿ‘คObed Ramales

0๐Ÿ‘

I think you need to set the country_id field in the AddressSerializer.

class AddressSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField()
    country = CountrySerializer(read_only = True)
    country_id = serializers.PrimaryKeyRelatedField(queryset = Country.objects.all(), source="country") #field added to get the id

    class Meta:
        model = Address
        fields = '__all__'
        extra_fields = ['country_id']

The country_id field is not defined in the Address class. So you need to set that field additionally.

๐Ÿ‘คMetalgear

Leave a comment