Mauricio
Mauricio

Reputation: 3089

Return list of objects within abject's attribute when many equals True, in Django Rest Framework

In DRF, how can I return a list of objects inside an array within an object's attribute, instead of a direct array.

Let's say I execute the following code:

people = Person.objects.all()
serializer = PersonSerializer(people, many=True)
print(serializer.data)

The output would be something the following:

[{'name': 'John'}, {'name': 'Rebbeca'}]

However, I would like it to be:

{'people': [{'name': 'John'}, {'name': 'Rebbeca'}]}

Upvotes: 0

Views: 71

Answers (1)

DeepSpace
DeepSpace

Reputation: 81624

Simply do:

people = Person.objects.all()
serializer = PersonSerializer(people, many=True)
serializer.data = {'people': serializer.data}
print(serializer.data)

Upvotes: 2

Related Questions