Files
breccia-mapper/people/views/export.py
James Graham 76270c4572 feat: Export relationships with answers
See #27
See #29
Resolves #25
2020-04-01 13:15:48 +01:00

37 lines
1.2 KiB
Python

import csv
import typing
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.views.generic.list import BaseListView
from .. import models, serializers
class CsvExportView(LoginRequiredMixin, BaseListView):
model = None
serializer_class = None
def render_to_response(self, context: typing.Dict) -> HttpResponse:
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = f'attachment; filename="{self.get_context_object_name(self.object_list)}.csv"'
# Force ordering by PK - though this should be default anyway
serializer = self.serializer_class(self.get_queryset().order_by('pk'), many=True)
writer = csv.DictWriter(response, fieldnames=serializer.child.column_headers)
writer.writeheader()
writer.writerows(serializer.data)
return response
class PersonExportView(CsvExportView):
model = models.Person
serializer_class = serializers.PersonExportSerializer
class RelationshipExportView(CsvExportView):
model = models.Relationship
serializer_class = serializers.RelationshipSerializer