i was looking through the django documentation on how to export my data to a CSV file so it can be imported into excel. So far i got it working but im having a bit of trouble figuring out how i can export the ManyToMany Fields in my models.
So far i have
writer = csv.writer(response)
writer.writerow(['A','B', 'C', 'D'])
for x in case_log_list:
writer.writerow([x.A,
x.B,
for y in x.C.all:
y,
x.D)
where the for loop inside the [list] is where i was trying to iterate over the ManyToMany Objects in that field. However i keep getting a syntax error that doesn’t make any sense.. am i even going about this correctly?
]on your list definition.Is x.C a list or sequence of some kind? Is your intent to write each item of x.C as a separate field in the CSV?
I believe you intended to use the list concatenation operator
+, which takes two lists and glues them together into one list. Use it like so:Your example becomes:
Or if you want to be brief:
Notes:
If
x.C.allis already a list – that is, iftype(x.C.all) is listisTrue– then[x.A, x.B] + x.C.all + [x.D,]will suffice.c_list = [item for item in x.C.all]is a list comprehension, which lets you do things to a list without having to write aforloop.List comprehensions are very powerful, very elegant and you should use them whereever it makes sense to do so. Any time you need to make a list based on another list, filter items in a list by some criteria, or both at the same time, a list comprehension is probably a good way to go.
Single-letter variable names like
x,A,B,C,Dare really terrible because they give no information about what data the variable holds, what its type may be, what values it might contain, etc. Use more descriptive variable names if you can.