django-commons / drf-excel

An XLSX spreadsheet renderer for Django REST Framework.
BSD 3-Clause "New" or "Revised" License
217 stars 40 forks source link

How to without serializer #75

Closed Mte90 closed 2 months ago

Mte90 commented 1 year ago

So for reasons I have the endpoint and I do some various manipulation aggregating various stuff (without a model) and generating a dict with the data that I want in the exported file. An example of my code:

class Export(XLSXFileMixin, Viewset):

    queryset = ""
    renderer_classes = (XLSXRenderer,)
    filename = "export.xlsx"

    http_method_names = [
        "get",
    ]

    def list(self, request):        
        new_output = {}
        if self.request.query_params.get("export") == "data":
            self.column_header = {
                "titles": [
                    [...]
                ]
            }
            [my code here]
        return self.response(new_output)

I get

AssertionError at /api/export/

'Export' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method.

So What is the right serializer to use to get just this dict in the generated file?

FlipperPA commented 1 year ago

The rendering code relies on customizing the Serializer. Can you try passing the DRF generic one?

from rest_framework.serializers import Serializer

class Export(XLSXFileMixin, Viewset):

    queryset = ""
    serializer_class = Serializer
    renderer_classes = (XLSXRenderer,)
    filename = "export.xlsx"

    http_method_names = [
        "get",
    ]

    def list(self, request):        
        new_output = {}
        if self.request.query_params.get("export") == "data":
            self.column_header = {
                "titles": [
                    [...]
                ]
            }
            [my code here]
        return self.response(new_output)
Mte90 commented 1 year ago

I tried with that one but didn't worked. Seems that required the various fields (with a field that doesn't exist in the serializer itself) define otherwise wasn't generating anything. Investigating the code seems that for any row and any value check if exist in the fields, so share like a json with the data is not working for this package (also the column headers were defined).

At the end I did it manually generating a csv for the moment.