How to get single nested child object in parent serialized object when models are foreign key related?
I have related models like:
class ModelC(models.Model):
name = models.CharField()
class ModelA(models.Model):
state = models.Charfield()
modelc = models.ForeingKey(ModelC, through='ModelAModelCRelation')
class ModelAModelCRelation(models.Model):
modelc = models.ForeignKey(ModelC)
modela = models.ForeignKey(ModelA)
class ModelAChild(models.Model):
parent_model = models.ForeignKey(ModelA)
active = models.BooleanField(default=True)
type = model.CharField(choices=['a', 'b', 'c', 'd'])
updated_at = models.DateTimeField()
- ModelC is related to ModelA with many to many relation,
- ModelA is related to ModelC throug ModelAModelCRelation relation,
- ModelAChild is related to ModelA with ForeignKey, which have many records related with ModelA record
And the related serializers are:
class ModelCSerializer(serializers.ModelSerializer):
modelA_objects = ModelASerializer(many=True, read_only=False)
class Meta:
model = ModelC
fields = StateBaseSerializer.Meta.fields + [
"id",
"name",
"modelA_objects",
]
class ModelASerializer(serializers.ModelSerializer):
modelAChild_objects = ModelAChildSerializer(many=True, read_only=True)
class Meta:
model = ModelA
fields = (
'id',
'state',
'modelAChild_objects',
)
class ModelAChildSerializer(serializers.ModelSerializer):
class Meta:
model = ModelAChild
fields = (
'id',
'active',
'type',
)
This approach is returning result like this:
[
{
'modelC_obj': {
'id': x,
'name': 'object name',
'modelA_obj': [
{
'id': 1,
'state': 'state name',
'modelAChild_obj': [
{
'id': 1,
'active': true,
'type': 'a'
},
{
'id': 2,
'active': false,
'type': 'b'
},
{
'id': 3,
'active': true,
'type': 'd'
},
]
}
]
}
}
]
But, I need a serialized result like:
[
{
'modelC_obj': {
'id': x,
'name': 'object name',
'modelA_obj': [
{
'id': 1,
'state': 'state name',
'modelAChild_obj': {
'id': 1,
'active': true,
'type': 'a'
}
}
]
}
}
]
I tried many querying method with Case
When
approach used in Subquery
.
But I cant made it to fetch only one ModelAChild
record to serialize.
What is the proper query and serializers to return result like the above?