Reputation: 393
I have a models.py
having:
class Other(models.Model):
name = models.CharField(max_length=200)
class ModelA(models.Model):
name = models.CharField(max_length=200)
other = models.ForeignKey(Other, on_delete=models.PROTECT)
in my rest API i want to retrieve as JsonResponse a json like this:
{
"modelA": {
"id": "modelA id automatically assigned by django model",
"name": "my modelA name",
"other": {
"id": "other thing id also automatically assigned by django model",
"name": "other thing name"
}
}
}
What is the most "pythonic" way to do it?
Upvotes: 1
Views: 488
Reputation: 5968
What you are looking for is nested serialization.
In your serializers.py
you should use the serializer for the Other
model inside the one for your ModelA
.
In serializers.py
:
from rest_framework import serializers
from .models import Other, ModelA
class OtherSerializer(serializers.ModelSerializer):
class Meta:
model = Other
fields = ('id', 'name')
class ModelASerializer(serializers.ModelSerializer):
other = OtherSerializer(read_only=True)
# The magic happens here.
# You use your already created OtherSerializer inside the one for ModelA
# And that will perform nested serialization
# Which will produce the result that you want
class Meta:
model = ModelA
fields = ('id', 'name', 'other')
# _________________________^
And now you get result like:
{
"id": 1,
"name": "my modelA name",
"other": {
"id": 1,
"name": "other thing name"
}
}
Upvotes: 2