0
votes

I am building API from django rest framework. I have a model in which there are certain foreign keys. For that model listing I am using ListAPIView. In that listing I want to implement nested queryset. Foreign key models are not directly in relation with each other. In following example. For multiple x there can be multiple y and for multiple y there can be multiple z. So I want json response as for unique x and in that object its y and its z.

I tried with annotate and subquery. But that does not seem to solve my issue.

Table: 
|x_id | y_id | z_id |
|1    | 2    | 3    |
|1    | 4    | 5    |
|1    | 2    | 6    | 
class Workitem(models.Model):
{ 
  x_id = # foreign key
  y_id = # foreign key
  z_id = # foreign key
}
class x(models.Model):
{ 
  x_id = 
  x_name = 
  x_details = 
}
class y(models.Model):
{ 
  y_id = 
  y_unique_name = 
  y_task_details = 
}
class z(models.Model):
{ 
  z_id = 
  z_acc_name = 
  z_acc_details = 
}
class WorkitemSerializer(serializers.ModelSerializer)
    class Meta:
            model = Workitem
            fields = '__all__'
            depth=2

Current I am getting JSON response a

{
    "count": 1,
    "next": null,
    "previous": null,
    "results":
       [
        { "x_id": {"x_details"},
          "y_id": {"y_details"},
          "z_id": {"z_details"}
        }
       ]
}

I want response as

{
    "count": 1,
    "next": null,
    "previous": null,
     results: ["x_id":{
                       "x_details":
                        "y_id": {
                                 "y_details":
                                 "z_id": {
                                         "z_details":
                                         }
                                },
                       },
                ]
}
1

1 Answers

0
votes

For that sort of a response you need to make chain the serializers

from rest_framework import serializers
class zserializer(serializers.ModelSerializer)

      class Meta:
          model = zModel
          fields = '__all__'

class yserializer(serializers.ModelSerializer)
      zobjects = zserializer(many=True)
      class Meta:
          model = yModel
          fields = ('id', 'zobjects')


class xserializer(serializers.ModelSerializer)
      yobjects = yserializer(many=True)
      class Meta:
          model = xModel
          fields = ('id', 'yobjects')

Then in the view use the xserializer for listing. Let us know if this solves your query.