python写csv Django for循环

时间:2012-10-15 11:13:41

标签: python django csv file-io

我在使用python csv库编写csv文件时有点困惑。我正在使用Django将信息从数据库中提取到对象中。

我现在拥有的,有效但尚未完成:

writer.writerow([Itag.Gen_ID if Itag else '',
     Itag.Solyc if Itag else '',
     Itag.GO_number if Itag else '',
     Itag.GO_def if Itag else '',
     Itag.Itag_description if Itag else '',
     Itag.IPR_Number if Itag else '',
     Itag.IPR_Description if Itag else '',
     Itag.Trivial_name if Itag else '',
     Loci.Locus_symbol if Loci else '',
     Loci.Locus_name if Loci else '',])

如果存在对象,则会将对象信息写入CSV文件。 现在在下一部分我有一个名为Blast的对象, Blast有几个属性: Blast.name, Blast.hit, Blast.score 对象ItagLoci具有一对一的关系,这就是为什么它们可以很好地连接在一起。

现在Blast对象与ItagLoci有多个关系 所以5 Blast次点击可以与1 Itag and Loci点击有关系。

现在如何将所有5个Blast对象属性写入CSV文件中的同一行?

1 个答案:

答案 0 :(得分:0)

这是不整洁的,但最明显的解决方案是将命中追加到该行:

<all that other stuff>, first_blast_name, first_blast_hit, first_blast_score, second_blast_name, second...<and so on>

我个人很少,如果有的话,这样做。我宁愿为loci创建一个csv文件,为blast创建另一个csv文件。