Search code examples
djangocsvdjango-querysetdrf-queryset

Django - values_list CSV


I'm trying to export CSV in Django and using values_list to select field i want to export.

My First Try

class ExportCSV(APIView):
    def get(self, request, *args, **kwargs):
        incidents = Incident.objects.filter(
            interview_date__range=(start, end),
            partner__twg=self.request.query_params.get("twg"),
        )

        for incident in incidents:
            writer.writerow(
                [
                    incident.incidenttwg1.getchild.values_list(  # <-- This line
                        "choice", flat=True
                    )
                ]
            )

I got this. <QuerySet ['Hello', 'Gudbye']>, so i decide to create loop to fetch Hello and Gudbye.

Here my second Try

class ExportCSV(APIView):
    def getincident(self, request, incident):  # Create a function
        for incident in incident.incidenttwg1.getchild.values_list("choice", flat=True):
            return incident

    def get(self, request, *args, **kwargs):
        incidents = Incident.objects.filter(
            interview_date__range=(start, end),
            partner__twg=self.request.query_params.get("twg"),
        )

        for incident in incidents:
            writer.writerow([self.getincident(request, incident)])  # Call function

I create a getincident function to make it cleanable to read.

what i got is Hello, its suppose to be Hello and Gudbye not only Hello.

Any Help?? Thanks....


Solution

  • I presume you're taking about the function getincident?

    You are only getting the first value because of of the return statement location.

    def getincident(self, request, incident): # Create a function
        return [incident for incident in incident.incidenttwg1.getchild.values_list('choice', flat=True)]
    

    this should give you all the values, in a list.