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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With