1

I have the following models:

class Person(models.Model):
    name = models.CharField(max_length=45)
    etc...

class Clothes(models.Model):
    person = models.ForeignKey(Person)
    etc...

I have the following in admin.py

class ExportCsvMixin:
    def export_as_csv(self, request, queryset):
        meta = self.model._meta
        field_names = [field.name for field in meta.fields]
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
        writer = csv.writer(response)
        writer.writerow(field_names)
        for obj in queryset:
            row = writer.writerow([getattr(obj, field) for field in field_names])
        return response
    export_as_csv.short_description = "Export Selected as CSV"


class PersonAdmin(admin.ModelAdmin, ExportCsvMixin):
    actions = ["export_as_csv"]
    etc...

This works great and I can export a csv file with all the fields from Person. How would I go about including the most recent record of the Clothes model as a field to the csv export?

Fish
  • 215
  • 1
  • 9
  • I think you might get what u need like this: `persons = Person.objects.all()` and next `personA_clothes = persons[0].clothes_set.all().order_by('id').last()` – Chiefir May 10 '18 at 23:29

1 Answers1

0

You have to add manually in your field_names and row list.

i.e.

    field_names = [field.name for field in meta.fields]
    field_names.append('recent_cloth')
    ...
    field_names.pop('recent_cloth')
    for obj in queryset:
        cloth = obj.cloth_set.first()
        row_list = [getattr(obj, field) for field in fields_names].append(cloth.name)
        row = writer.writerow([getattr(obj, field) for field in field_names])

Or if you make your own queryset with select_related and annotate, you can use cloth field with object.

seuling
  • 2,850
  • 1
  • 13
  • 22