1

I have an API. I want to change it so it will look like so:

[
    cats: [{
            "id": 1,
            "description": "I lost my mind",
            "petName": "kappies",
            "phone": 56765665464
        },
        {
            "id": 2,
            "description": "I lost my dog somewhere",
            "petName": "Doggy",
            "phone": 38093716438
        }
    ],
    dogs: [{
            "id": 3,
            "description": "",
            "petName": "",
            "phone": 0
        }, 
        {
            "id": 3,
            "description": "",
            "petName": "",
            "phone": 0
        }
    ]
]

Who knows how can I do it?

Do I need to create API for cats and dogs separately?

sry for cups. serializers

1
  • Welcome to Stackoverflow. If you found any of the answers useful you should consider up-vote and select the correct answer :) Commented Mar 25, 2018 at 12:22

1 Answer 1

1

Lets say you got type field in your model.

You can then do something like so in your view.py:

posts = models.Post.objects.all()
posts_serializer = serializers.PostSerializer(posts, many=True)

output = {}
for post in posts_serializer.data:
    type = output.get(post['type'], [])
    output[type].append(post)

return Response(output)

You should add more code and what you tried to do next time you are asking a question.

Good Luck

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.