DJANGO: How to Output CSV with model containing many-to-many field?

笑着哭i 提交于 2020-01-03 03:49:05

问题


I have an "Export to CSV" button that exports all car models. When I export all cars into CSV, the "features" (e.g. AM/FM Radio, Moon Roof, Leather Interior, Bluetooth, GPS etc..) column displays as the following:

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

How do I get rid of all that other stuff, and just have "GPS, Leather"?

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

ANSWER:

MODELS:

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

VIEWS:

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:


Depends on what field you want to print in the features model... You are looking at an m2m manager - it's a helper that returns a queryset interface. If you want all related features, you'd want to call x.features.all()

Replace with your actual field on the features model.

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


来源:https://stackoverflow.com/questions/10455753/django-how-to-output-csv-with-model-containing-many-to-many-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!