Created
August 6, 2015 09:27
-
-
Save niktto/028a2adc5ad943ff9702 to your computer and use it in GitHub Desktop.
Using Django Rest Framework to ease csv generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
class SomeModel(models.Model): | |
email = models.EmailField() | |
first_name = models.CharField(max_length=50) | |
last_name = models.CharField(max_length=50) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework import serializers | |
from .models import SomeModel | |
class SomeModelSerializer(serializers.ModelSerializer): | |
class Meta: | |
model = SomeModel | |
fields = ( | |
'email', | |
'first_name', | |
'last_name', | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
from django.views.generic import View | |
from django.http import HttpResponse | |
from .serializers import SomeModelSerializer | |
from .models import SomeModel | |
class SomeModelCSVExportView(View): | |
serializer_class = SomeModelSerializer | |
def get_serializer(self, queryset, many=True): | |
return self.serializer_class( | |
queryset, | |
many=many, | |
) | |
def get(self, request, *args, **kwargs): | |
response = HttpResponse(content_type='text/csv') | |
response['Content-Disposition'] = 'attachment; filename="export.csv"' | |
serializer = self.get_serializer( | |
SomeModel.objects.all(), | |
many=True | |
) | |
header = SomeModelSerializer.Meta.fields | |
writer = csv.DictWriter(response, fieldnames=header) | |
writer.writeheader() | |
for row in serializer.data: | |
writer.writerow(row) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this just helped me to solve some issues I was having