Longform thoughts of @rajasimon

How to convert Django Queryset into Pandas Dataframe?

Published 2 Jan, 2022

Pandas dataframe is the structure of content in this article I'm talking about how to convert a Django queryset into one.

When working on the project where you need to do more of the after calculation, the calculation where you need third party support for you Django project. I was in that situation and I’ve chosen Pandas for it. I was working on the problem where I need to calculate mean value for multiple clients that is in the queryset. Now you may think why can’t do that in queryset operation itself. I don’t think that is possible cause we are talking about the multiple clients and I need the output in the different format. So I decided to use Pandas because the calculation are super easy and can generate highly customisable output.

Whenever you have queryset to convert into dataframe there is a values in the queryset function object that we can use it to generate the list. i.e)

datas = Data.objects.filter(datetime__gte=data_from, datetime__lte=data_to)
datas = list(datas.values("datetime", "reading", "customer_id", "device_id"))

Now that we have the list of those values we can pass this into data frame constructor like this.

df = pd.DataFrame(
        datas.values("datetime", "reading", "customer_id", "device_id")

This article published under development on pandas tags. Please subscribe below forms to receive articles.

Join the Newsletter

Subscribe to get our latest content by email.
    We won't send you spam. Unsubscribe at any time.