Home » excel » python – Django CSV Export.. Iterating inside a list

python – Django CSV Export.. Iterating inside a list

Posted by: admin May 14, 2020 Leave a comment

Questions:

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?

How to&Answers:
  1. You’re missing a terminating ] on your list definition.
  2. You can’t put a for loop inside a list.

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:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]

Your example becomes:

for x in case_log_list:
    c_list = [item for item in x.C.all]          # turn x.C into a list
    output_list = [x.A, x.B] + c_list + [x.D,]   # assemble list
    writer.writerow( output_list )

Or if you want to be brief:

for x in case_log_list:
    writer.writerow ( [x.A, x.B] + [item for item in x.C.all] + [x.D,] )

Notes:

  • If x.C.all is already a list – that is, if type(x.C.all) is list is True – 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 a for loop.

    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, D are 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.

Answer:

You have to create data before inserting it in csv.

You can get all write data before doing write operation on that.

mydata = [x.A,x.B]

mydata += [y for y in x.C.all]
mydata.append(x.D)
# write mydata to the csv.

This way you will get the data and directly you can write to the csv.