在Django中生成TSV文件

时间:2010-01-14 19:10:50

标签: django

我想从车辆列表中生成一个TSV文件....我还将对数据进行一些转换,例如如果传输值为“自动”,则此值将呈现为“A”或如果里程为英里,则将此值乘以1.6。

最好的方法是什么?

更新

好的......所以我写了如下脚本:

from django.conf import settings
import myapp.settings
setup_environ(myapp.settings)

from django.db import models
from myapp.vehicles.models import Vehicle

import csv

data = Vehicle.objects.all().exclude(status__status='Internal Use').
   exclude(status__status='Sold').order_by('-common_vehicle__year',
   'common_vehicle__series__model__manufacturer__manufacturer',
   'common_vehicle__series__model__manufacturer__manufacturer_popularity')


vehicles = csv.writer(open('cars.csv', 'w'), delimiter='\t')
vehicles.writerow(["VIN","Stock","Year","Make","Model",
    "TrimPackage","Transmission","DriveType","Odometer","OdometerType",
    "Doors","BodyStyle","EngineType","Exterior","Interior","Condition",
    "Certified","FuelType","Price"])
for vehicle in data:
  vehicles.writerow(["1130","26919",vehicle.vin,vehicle.stock_number,
  vehicle.common_vehicle.year.year,
  vehicle.common_vehicle.series.model.manufacturer.manufacturer,
  vehicle.common_vehicle.series.model.model,vehicle.common_vehicle.series.series,
  transmission,vehicle.common_vehicle.drive_train.drive_train,
  vehicle.odometer_reading,"KM",vehicle.common_vehicle.body_style.doors,
  body_style,engine_type,vehicle.exterior_colour.exterior_colour,
  vehicle.interior_colour.interior_colour,"E","Y",fuel_type,"0"])

但是,当我尝试运行脚本时,我收到此错误:ImportError: No module named myapp.settings

更新2 刚看到我的错误......现在一切都好了

2 个答案:

答案 0 :(得分:6)

在Python中使用CSV support

dialect delimiter更改为标签。

链接页面有很多例子。

答案 1 :(得分:0)

您需要静态文件吗?或者您是否希望根据Django app中的其他内容动态生成此信息?

无论哪种方式,我认为Django模板系统可以正常工作。您需要做的就是使用您希望数据输入的格式设计模板。如果您需要静态文件,请创建一个将模板结果保存到静态文件的小脚本。