0

我正在尝试导出CSV in Django并使用values_list来选择我要导出的字段。

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
                    )
                ]
            )

我懂了。<QuerySet ['Hello', 'Gudbye']>,所以我决定创建loop来获取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

我创建了一个getincident函数来让它cleanable读取。

我得到的是Hello,它应该是Hello,而Gudbye不仅仅是Hello

有什么帮助吗??谢谢....

4

1 回答 1

0

我想你正在考虑这个功能getincident

由于return语句位置,您只能获得第一个值。

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

这应该在列表中为您提供所有值。

于 2020-08-13T04:57:35.323 回答