Daniel
Daniel

Reputation: 1061

Django: Model Queryset to Pandas to Django Rest Framework

I am trying to accomplish the following workflow in my Django project:

  1. Query my database
  2. Convert the returned queryset to a pandas dataframe in order to perform some calculations & filtering
  3. Pass the final dataframe to Django REST API Framework

if I understand correctly, I have to use django-pandas for Step 2. and Django REST Pandas for Step 3. I installed both and read the documentaton, but I have no clue how to make it work.

What I have achieved to far is to set up my model, views, serializes and urls to have the original queryset rendered via the Django Rest Framework.

If anyone could give me a hint on how to integrate pandas in this workflow, it would be highly appreciated.

my models.py file

from django.db import models

class Fund(models.Model):
    name = models.CharField(max_length=100)
    commitment_size = models.IntegerField(blank=True, null=True)
    commitment_date = models.DateField(blank=True, null=True)

    def __str__(self):
        return self.name

my views.py file

from rest_framework import generics
from rest_framework.views import APIView

from pages.models import Fund
from .serializers import FundSerializer

class FundAPIView(generics.ListAPIView):
    queryset = Fund.objects.all()
    serializer_class = FundSerializer

my serializers.oy file

from rest_framework import serializers

from pages.models import Fund

class FundSerializer(serializers.ModelSerializer):
    class Meta:
        model = Fund
        fields = ('name', 'commitment_size', 'commitment_date')

Upvotes: 3

Views: 3908

Answers (1)

Daniel
Daniel

Reputation: 1061

So i figured it out. First, you need to install django-pandas and django rest framework (but no need to install django REST pandas)

models.py and serializers.py files stay the same as above, but the views file is different

from rest_framework.views import APIView
from rest_framework.response import Response

from django_pandas.io import read_frame   # Import django_pandas.io read frame

from pages.models import Fund
from .serializers import FundSerializer

class TestData(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        data = Fund.objects.all()        # Perform database query
        df = read_frame(data)            # Transform queryset into pandas dataframe 
        df['testcolumn'] = "testdata"    # Perform some Pandas Operation with dataframe
        return Response(df)              # Return the result in JSON via Django REST Framework

Upvotes: 4

Related Questions