thedeepfield
thedeepfield

Reputation: 6196

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

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

Upvotes: 1

Views: 2088

Answers (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()])

Upvotes: 4

Related Questions