1

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.

talz
  • 1,004
  • 9
  • 22

2 Answers2

0

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)
Asabuas
  • 11
  • 4
  • This suggestion doesn't work, this just returns one list of `field1`, and the annotations (that I did add) do not do anything when using `values_list`. – talz Jan 19 '21 at 09:04
0

If you use PostgreSQL you can tray to use:

arrayagg

den
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 27 '21 at 14:33
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30682357) – Nico Haase Dec 31 '21 at 13:05