Shahabaz
Shahabaz

Reputation: 665

Django Rest Framework - How to save using id and retrieve other columns as well?

This question is a continuation of other question from this link here(Django Rest Framework how to save a model with Related Field based on ID)

My situation got solved when I used PrimaryKeyRelatedField() to store data using id on a POST request. This, in turn, created another issue. I was using the same API's GET option to list all the columns from the related (Foreign Key referred)model, after using PrimaryKeyRelatedField() the other columns got disappeared and ID is only showing up. Need help on this.

To be more clear need ID column of the referred table during POST call and need other columns of the model/table during GET call.

PS: I have used serializers.ModelSerializer method

Upvotes: 1

Views: 1752

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

You can use serializer's to_representation method to override related objects field only for output data. For example you can use sested serializer to show related object details, like this:

class RelatedSerializer(serializers.ModelSerializer):
    class Meta:
        Model = RelatedModel
        fields = ('id', 'field1', 'field2')

class YourSerializer(serializers.ModelSerializer):
    related_field = serializer.PrimaryKeyRelatedField(queryset=RelatedModel.objects.all())
    class Meta:
        Model = SomeModel 
        fields = ('id', 'related_field')

    def to_representation(self, instance):
        self.fields['related_field'] = RelatedSerializer()
        return super(YourSerializer, self).to_representation(instance)

Upvotes: 4

Related Questions