I'm working on a django web app which visualizes data stored in a SQLite in the browser using bokeh.
Since I want to display the data as a stacked area plot I concluded it might be helpful to use the pandas library to save the data from my django model to a dataframe before plotting.
My Django models.py
includes the following model:
class Activity(models.Model):
def __str__(self):
return self.title
title = models.CharField(max_length=50)
sport = models.ForeignKey(Sport, on_delete=models.CASCADE)
date = models.DateField(blank=False)
duration = models.FloatField()
distance = models.FloatField(blank=True, null=True)
description = models.CharField(max_length=50, blank=True, null=True)
trace_file = models.ForeignKey(TraceFiles, on_delete=models.CASCADE, blank=True, null=True)
Some example data in the SQLite db could look similar to:
| id | title | date | duration | sport_id | trace_file_id | description | distance |
|--------------------------------------------------------------------------------------------|
| 1 | biking01 | 2019-01-01 | 183 | 1 | 16 | NULL | 142 |
| 2 | running17 | 2019-01-01 | 45 | 2 | 2 | NULL | 14 |
| 3 | biking02 | 2019-01-01 | 67 | 1 | 18 | NULL | 45 |
What would be the best way to read from the model and convert the data to a pandas dataframe? For example I have similar code in my views.py
:
from .models import Activity
import pandas as pd
activities = Activity.objects.all().order_by("-date")
...
Similar to the dataframe in this example I'd like to get a dataframe which looks like the following, so I can plot a bokeh area plot.
sport_id duration date
0 1 183 2019-01-02
1 1 67 2019-05-06
2 2 45 2019-03-04
Any help is appreciated.