【问题标题】:Django - values_list CSVDjango - values_list CSV
【发布时间】:2020-08-13 04:35:57
【问题描述】:

我正在尝试导出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
                    )
                ]
            )

我明白了。 &lt;QuerySet ['Hello', 'Gudbye']&gt;,所以我决定创建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,它应该是HelloGudbye 而不仅仅是Hello

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

【问题讨论】:

    标签: django csv django-queryset drf-queryset


    【解决方案1】:

    我猜你是在讨论getincident这个函数?

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

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

    这应该给你所有的值,在一个列表中。

    【讨论】:

    • 我尝试使用yield,但得到了这个&lt;generator object at 0x7f00ccf56ba0&gt;
    • 你是对的,再次检查你的原始代码,我会使用 2second 选项。我将删除 yield 方法。
    猜你喜欢
    • 2016-09-09
    • 2011-07-09
    • 1970-01-01
    • 2012-01-25
    • 2016-08-02
    • 2011-09-18
    • 2013-04-18
    • 2011-06-16
    • 1970-01-01
    相关资源
    最近更新 更多