1
- import csv
1
+ import csv
2
2
import six
3
3
from six import text_type
4
4
5
5
from django .http import HttpResponse
6
6
7
7
8
8
class LUT (object ):
9
-
9
+
10
10
def __init__ (self ):
11
11
self .lut = []
12
-
12
+
13
13
def add_field (self , field_name ):
14
14
""" """
15
15
if field_name not in self .lut :
16
16
self .lut .append (field_name )
17
-
17
+
18
18
def get_idx (self , field_name ):
19
19
""" """
20
20
return self .lut .index (field_name )
21
-
22
-
23
-
21
+
22
+
23
+
24
24
def export_as_csv_action (description = "Export selected objects as CSV file" ,
25
25
fields = None , exclude = None , header = True , json_fields = None ):
26
26
"""
27
27
This function returns an export csv action
28
28
'fields' and 'exclude' work like in django ModelForm
29
29
'header' is whether or not to output the column names as the first row
30
-
30
+
31
31
json_fields will be exploaded to rows.
32
32
"""
33
33
@@ -50,7 +50,7 @@ def export_as_csv(modeladmin, request, queryset):
50
50
51
51
response = HttpResponse (content_type = 'text/csv' )
52
52
response ['Content-Disposition' ] = 'attachment; filename=%s.csv' % text_type (opts ).replace ('.' , '_' )
53
-
53
+
54
54
writer = csv .writer (response )
55
55
"""
56
56
if header:
@@ -74,13 +74,13 @@ def export_as_csv(modeladmin, request, queryset):
74
74
j = getattr (obj , field )
75
75
for l in j :
76
76
try :
77
- for k , v in l .iteritems ():
77
+ for k , v in l .items ():
78
78
lut .add_field (k )
79
79
except AttributeError :
80
80
pass
81
81
else :
82
82
lut .add_field (field )
83
-
83
+
84
84
if header :
85
85
writer .writerow (lut .lut )
86
86
for obj in queryset :
@@ -89,7 +89,7 @@ def export_as_csv(modeladmin, request, queryset):
89
89
if field in json_fields :
90
90
j = getattr (obj , field )
91
91
for l in j :
92
- for k , v in l .iteritems ():
92
+ for k , v in l .items ():
93
93
try :
94
94
s = text_type (v )
95
95
if six .PY2 :
@@ -102,8 +102,8 @@ def export_as_csv(modeladmin, request, queryset):
102
102
for field in many_to_many_field_names :
103
103
row [lut .get_idx (field )] = text_type (getattr (obj , field ).all ())
104
104
writer .writerow (row )
105
-
106
-
105
+
106
+
107
107
return response
108
108
export_as_csv .short_description = description
109
- return export_as_csv
109
+ return export_as_csv
0 commit comments