Django export filtered query to csv
<p>So the scenario is this: I have a search form where the user types or selects the criteria. These criteria are being posted and I get a query in returned, filtered with these criteria. The code for the search form is similar to the code shown below.  </p>

<p>What I want to do now is take these results and export them in <code>csv</code> file. So, as I said I have almost the same code where I get my params/criteria with GET. Basically I GET the criteria the user has typed or selected after the search POST was made. </p>

<p>So far, I have succesfully got the params, I can see them in print, and the export is down but I can see only the first row. It's like I can't pass the query (as provided in results).</p>

<p>Here's my code:</p>

<pre><code>    def get_csv(request):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=mycsv.csv'
        if request.method == 'GET':
            params = {}
            your_values = {}
            context = {}
            field_1 = request.GET.get('field_1',None)
            field_2 = request.GET.get('field_2',None)
            field_3 = request.GET.get('field_3',None)
            if field_1:
                your_values['field_1'] = field_1
            if field_2:
                your_values['field_2'] = field_2
            if field_3:
                your_values['field_3'] = field_3
            if field_4:
                your_values['field_4'] = field_4
            for key, value in your_values.items():
                if value:
                    params[key] = value
                print('params are:',params)
            results = Model.objects.filter(**params)
            writer = csv.writer(response)
            writer.writerow([h for h in [
                'Header_1',
                'Header_2',
                'Header_3',
                'Header_4',
                ]])
          #I tried that as well:writer.writerows([r for r in[results]])
            for field in results:
                field_list = [
                field.filed_1,
                field.field_2,
                field.field_3,
                field.field_4,
               ]
            for i, item in enumerate(field_list):
                if item:
                    field_list[i] = item
                    writer.writerow(field_list)
        return response
</code></pre>

<p>Youre seeing only one row because youre passing only one row:</p>

<pre><code>for field in results:
     field_list = [
     field.filed_1,
     field.field_2,
     field.field_3,
     field.field_4,
     ]
</code></pre>

<p>The above puts only the item from the last iteration in <code>field_list</code> and the previous results are thrown away.</p>

<p>You can instead use a <em>list comprehension</em> to create the list of lists adding the indices at the same time using <code>enumerate</code>. And then write all the rows at the same time using <code>writerows</code>:</p>

<pre><code>results = Model.objects.filter(**params)
writer = csv.writer(response)
writer.writerow(['Header_1', 'Header_2', 'Header_3', 'Header_4'])     
field_list = [[i, f.field_1, f.field_2, f.field_3, f.field_4] 
                         for i, f in enumerate(results) if f]
writer.writerows(field_list)
#              ^ notice the s
</code></pre>

python django csv