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.
What I want to do now is take these results and export them in csv
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.
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).
Here's my 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
Youre seeing only one row because youre passing only one row:
for field in results:
field_list = [
field.filed_1,
field.field_2,
field.field_3,
field.field_4,
]
The above puts only the item from the last iteration in field_list
and the previous results are thrown away.
You can instead use a list comprehension to create the list of lists adding the indices at the same time using enumerate
. And then write all the rows at the same time using writerows
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.