问题描述
我正在尝试导出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,incident): # Create a function
for incident in incident.incidenttwg1.getchild.values_list("choice",flat=True):
return incident
def get(self,)
for incident in incidents:
writer.writerow([self.getincident(request,incident)]) # Call function
我创建了一个getincident
函数以使其cleanable
可以读取。
我得到的是Hello
,它应该是Hello
和Gudbye
,而不仅仅是Hello
。
有帮助吗??谢谢......
解决方法
我想您正在使用功能getincident
?
由于return
语句的位置,您只会得到第一个值。
def getincident(self,request,incident): # Create a function
return [incident for incident in incident.incidenttwg1.getchild.values_list('choice',flat=True)]
这应该在列表中为您提供所有值。