From model data to csv file in Django Rest Framework

Osirus Djodji
3 min readJan 24, 2023

--

Django is the web development framework in python whereas the Django Rest Framework is the library used in Django to build Rest APIs. Django Rest Framework is especially designed to make the CRUD operations easier to design in Django. Django Rest Framework makes it easy to use your Django Server as an REST API.

We will go from the state of data stored in a table to a csv file containing this data.

Let’s start by installing drf in our django project:

pip install djangorestframework

Add ‘rest_framework’ to your INSTALLED_APPS setting.

INSTALLED_APPS = [

‘rest_framework’,

]

Add the following to your root urls.py file.

urlpatterns = [

path(‘api-auth/’, include(‘rest_framework.urls’))
]

We will create a Product model:

from django.db import models


class Category(DeiObject):
slug = models.CharField(max_length=45)
name = models.CharField(max_length=225)


class Product(models.Model):
ref = models.CharField(max_length=64, help_text=”Product ref”, unique=True)
name = models.CharField(max_length=125, help_text=”Name of the product”)
date_of_storage = models.CharField(max_length=255, null=True, blank=True)
price = models.DecimalField(max_digits=12, decimal_places=2, help_text="Category of the product")
category = models.ForeignKey(Category, on_delete=models.CASCADE)

The serializer:

from rest_framework import serializers
from yourapp.product.models import Product


class ProductSerializer(serializer.ModelSerializer):
class Meta:
model = Product
fields = (
id’,
‘ref’,
‘name’,
‘date_of_storage’,
‘price’,
‘category’,
)

Let’s install pandas. Pandas is a software library written for the Python programming language for data manipulation and analysis.

pip install pandas

The viewset:

from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from rest_framework.views import APIView
from yourapp.products.models import Product
from yourapp.products.serializers import ProductSerializer


class ProductViewSet(ModelViewset):
“””Return the list of **products**“””
serializer_class = ProductSerializer
queryset = Product.objects.all()
permission_classes = [permission.IsAuthenticatedOrReadOnly]


class ExportProductsAPI(APIView):
def get(self, request):
products_objs = Products.objects.all()
serializer = ProductsSerializer(status_objs, many=True)
df = pd.DataFrame(serializer.data)
df.to_csv(f”export/excel/products/{uuid.uuid4()}.csv”, encoding=”UTF-8", index=False)
return Response({‘status’: 200})

And the router:

# ##################################################################### #
# ############################## PRODUCTS ############################# #
# ##################################################################### #
router.register(‘products’, ProductViewSet, basename=’products’)

Don’t forget to add the export url in the ulrs.py file.

urlpatterns = [
path(‘api/export/products/’, ExportProductsAPI.as_view(),name=’products_export’),
]

Create the path export/excel/products from the root directory of your project.

Use http://127.0.0.1:8000/api/v1/export/products/ to generate the file.

Your file should look like this:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response