Reputation: 1200
Using Django-REST-framework, I have the following view:
class MyRESTfulAPIView(APIView):
permission_classes = [IsAuthenticated, MyCustomPermision]
def get(self, request):
data = MyModel.objects.values('field1').annotate(field2=..., field3=...)
return Response(data)
Which returns a JSON with the shape:
[
{'field1': Result1.field1, 'field2': Result1.field2, 'field3': Result1.field3},
{'field1': Result2.field1, 'field2': Result2.field2, 'field3': Result2.field3},
...
]
Is there a way to get each column as a list of values, like this:
{
'field1': [Result1.field1, Result2.field1, ...],
'field2': [Result1.field2, Result2.field2, ...],
'field3': [Result1.field3, Result2.field3, ...],
}
The exact shape of the JSON is not important, just getting each "column" (model field) as one list of all values, instead of each row as a dictionary. (Because the data then gets passed to a library that expects the data to be in separate lists)
Obviously I could just unpack the QuerySet and restructure it with Python (for example like in that answer), but I am looking for some way to tell either Django or DRF to build the JSON like that in the first place instead having Django and DRF build the result one way and then iterate over the result again to restructure it.
Upvotes: 1
Views: 1441
Reputation: 21
you can use values_list to get a single field in list format then use annotate. I didn't tried it though
data = MyModel.objects.values_list('field1',flat=true)
Upvotes: 1