How to create Id based PUT/POST but details in the response in DRF?

Viewed 1820

I have a situation where a model has a foreign key with details. Ex. there are two models

class Person(models):
    country = models.ForeignKey(Country)

class Country(models):
    name = models.CharField(max_length=100)

Assume countries have been created beforehand. Now, I want the APIs for Person to take only country Id in POST/PUT requests but return the details of that country instead of only Id.

Request
{
   "id": 1,
   "country": 9
}
Response
{
   "id": 1,
   "country": {
       "id": 9,
       "name": "Some Country"
    }
}

I'm using Django Rest Framework. (I can write serializers which either take id in both read and write APIs or take the entire country object)

1 Answers
Related