Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 953
Rubbal Avatar asked Nov 08 '22 19:11

Rubbal


1 Answers

You can write custom field CountryField for this and user to_representation method to return object details:

class CountryDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Country
        fields = ('id', 'name')

class CountryField(serializers.PrimaryKeyRelatedField):
    def to_representation(self, value):
        country = models.Barcode.objects.get(pk=value.pk)
        serializer = CountryDetailSerializer(country)
        return serializer.data

    def get_queryset(self):
        return Country.objects.all()

And use it in Person serializer:

class PersonSerializer(serializers.ModelSerializer):
    country = CountryField()
like image 86
neverwalkaloner Avatar answered Nov 15 '22 07:11

neverwalkaloner