У меня проблема с отображением данных в смешанную линейную и линейную диаграммы из API, разработанного с использованием Django Rest Framework. Вот модель для показаний датчиков давления и расхода
models.py
from django.db import models
# Create your models here.
class ReadingQuerySet(models.QuerySet):
pass
class ReadingManager(models.Manager):
def get_queryset(self):
return ReadingQuerySet(self.model, using=self._db)
class Reading(models.Model):
date = models.DateField(auto_now=True)
pressure =models.IntegerField(default=0)
flowrate =models.IntegerField(default=0)
timestamp =models.TimeField(auto_now_add=True)
objects = ReadingManager()
def __str__(self):
return str(self.timestamp) + ' ' + 'Pressure: ' + str(self.pressure) + ' ' + 'Flowrate: ' + str(self.flowrate)
Код для сериализатора находится здесь.
serializers.py
from rest_framework import serializers
from app.models import Reading
class ReadingSerializer(serializers.ModelSerializer):
class Meta:
model = Reading
fields = ['id','date','timestamp','pressure','flowrate']
сериализатор находится в папке API, я помещен в django приложение. код для просмотра API приведен ниже.
views.py
from rest_framework import generics, mixins
from rest_framework.response import Response
from .serializers import ReadingSerializer
from app.models import Reading
class ReadingChartAPIView(mixins.CreateModelMixin, generics.ListAPIView):
permission_classes = []
authentication_classes = []
serializer_class = ReadingSerializer
def get(self, request, *args, **kwargs):
qs = Reading.objects.all()
data = {
'timestamp':qs.values('timestamp'),
'pressure':qs.values('pressure'),
'flowrate':qs.values('flowrate'),
'update':qs.values('pressure', 'flowrate').last()
}
return Response(data)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
, и это данные, которые я получаю от APIview
{"timestamp":[{"timestamp":"12:44:11.487901"},{"timestamp":"14:12:58.410520"},{"timestamp":"01:56:56.485449"},{"timestamp":"01:57:14.184429"},{"timestamp":"01:57:34.366559"},{"timestamp":"13:12:43.469454"}],"pressure":[{"pressure":45},{"pressure":35},{"pressure":79},{"pressure":52},{"pressure":89},{"pressure":27}],"flowrate":[{"flowrate":56},{"flowrate":67},{"flowrate":83},{"flowrate":14},{"flowrate":74},{"flowrate":46}],"update":{"pressure":27,"flowrate":46}}
Проблема в моем файле html при извлечении этого данные. Вот мой HTML. Я застрял и открыт для любых решений. я пытаюсь набрать sh меток данных для наборов данных каждые 5 секунд, начиная с первой.
{% extends "layouts/base.html" %}
{%load static %}
{% block title %} Dashboard {% endblock %}
<!-- Specific Page CSS goes HERE -->
{% block stylesheets %}{% endblock stylesheets %}
{% block content %}
{% block jquery %}
<script type="text/javascript">
var counter = 0
var limit = 6
var chart = $('#myChart')
var endpoint = '/api/chart'
var pressures = []
var flowrates = []
var timestamps = []
var pressure_new = []
var flowrate_new = []
$.ajax({
method: 'GET',
url: endpoint,
success: function(data){
console.log(data)
}
})
var getData =
$.ajax({
method: 'GET',
url: endpoint,
success: function(data){
timestamps = data.timestamp.map(b => b.timestamp);
pressures = data.pressure.map(a => a.pressure);
flowrates = data.flowrate.map(c => c.flowrate);
myChart.data.labels.concat(timestamps[counter]);
myChart.data.datasets[0].data.concat(pressures[counter]);
myChart.data.datasets[1].data.concat(flowrates[counter]);
counter++;
myChart.update();
}
});
setInterval(getData, 3000)
</script>
{% endblock %}
<div class="container-fluid">
<div class="page-header row no-gutters py-4">
<div class="col-12 col-sm-4 text-center text-sm-left mb-0">
<span class="text-uppercase page-subtitle">Dashboard</span>
<h3 class="page-title">Overview</h3>
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-12 col-sm-12 mb-4">
<div class="card" width = '18rem' height = '10rem'>
<div class="card-header border-bottom">
<h5 class="card-title">Pressure and Flowrate</h5>
<h6 class="card-subtitle mb-1 text-muted">Real-time Readings of Pressure and Flowrate</h6>
</div>
<div class="card-body">
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script>
function setChart(){
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Pa',
data:[],
backgroundColor:'rgba(255, 99, 132, 0.2)',
borderColor:'rgba(255, 99, 132, 1)',
borderWidth: 1
}, {
label: 'cm3/min',
data:[],
backgroundColor:'rgba(54, 162, 235, 0.2)',
borderColor:'rgba(54, 162, 235, 1)',
type: 'line',
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
};
setChart()
</script>
</div>
</div>
</div>