DJANGO:如何使用包含多对多字段的模型输出CSV?

时间:2012-05-04 20:32:10

标签: django csv many-to-many export export-to-csv

我有一个“导出到CSV”按钮,可以导出所有车型。当我将所有汽车导出为CSV时,“功能”(例如AM / FM收音机,月亮屋顶,皮革内饰,蓝牙,GPS等)列显示如下:

[<Feature: GPS>, <Feature: Leather>]

如何摆脱所有其他东西,只有“GPS,皮革”?

MODEL

class Features(models.Model):
    name = models.CharField(max_length=20)
    def __unicode__(self):
       return self.name

class Car(models.Model):
    model_name = models.CharField(max_length=20)
    features = models.ManyToManyField(features)
    def __unicode__(self):
       return self.model_name

VIEW.PY

def query(request):
    results = Car.objects.all()
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment;filename="car_export.csv"'
    writer = csv.writer(response)
    writer.writerow(['Model Name', 'Features'])
    for x in results:
        writer.writerow([x.model_name, x.role.all()])
        return response

解答:

模型:

class Features(models.Model):
    name = models.CharField(max_length=20)
    def __unicode__(self):
       return self.name

class Car(models.Model):
    model_name = models.CharField(max_length=20)
    features = models.ManyToManyField(features)
    def __unicode__(self):
       return self.model_name

视图:

def query(request):
    results = Car.objects.all()
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment;filename="car_export.csv"'
    writer = csv.writer(response)
    writer.writerow(['Model Name', 'Features'])
    for x in results:
        writer.writerow([x.model_name, ', '.join([x.name for x in x.role.all()]),])
        return response

1 个答案:

答案 0 :(得分:2)

取决于您要在features模型中打印哪个字段...您正在查看m2m管理器 - 它是一个返回查询集界面的帮助程序。如果您需要所有相关功能,则需要致电x.features.all()

替换功能模型上的实际字段。

csv_features = ','.join([x.MY_FIELD_HERE for x in x.features.all()])