using primarykeyrelated for post and string for get call in django rest framework

120

Question: using primarykeyrelated for post and string for get call in django rest framework

I have a model in which some fields are a foreign key to another model. Hence while django error creating the object of that model I have to use primary key but while calling get api I need to show those fields as stringrelated field. How to achieve that??

My model:

class Example(models.Model):      tour = models.ForeignKey(         Package,         on_delete=models.CASCADE,         null=True,         related_name="example"     )      site = models.ForeignKey(                                 Destination,                                 on_delete=models.CASCADE,                                 null= True,                                 related_name= "example",     )            location = models.CharField(blank=True)     /...........other fields........../ 

My serializer:

class ExampleSerializer(serializers.ModelSerializer):      # tour = serializers.StringRelatedField()     # site = serializers.StringRelatedField()      class Meta:         model = OnlineClass         fields = ['id','tour','site','other fields.....']      def to_representation(self, instance):         data = super(ExampleSerializer, self).to_representation(instance)         return data 

Here while creating the example object, I need to pass tour and site as ids but while calling list method I need to show both fields as string related fields. As I define them as stringrelated field as above (later commented out) , I can create the object but those fields will django error be set as null. I don't want to make another serializer. How to achieve this??

Total Answers: 1

99

Answers 1: of using primarykeyrelated for post and string for get call in django rest framework

What you want is the the slug related field which can be used to target the id (or whatever field you want) of your targeted relation.

Something like :

tour= serializers.SlugRelatedField(     read_only=True,     slug_field='id' )