I have a django model which is called ScanBatch. Scan batch is made up of fields like the timestamp (datetime field), domain (char field) and total ids found (integer field).
My chart code is :
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: []
},
options: {
scales: {
yAxes: [{
id: 'A',
type: 'linear',
position: 'left',
}, {
id: 'B',
type: 'linear',
position: 'right',
ticks: {
max: 1,
min: 0
}
}]
}
}
});
models code is
class ScanBatch(models.Model):
domain = models.CharField(max_length=255)
timestamp = models.DateTimeField(auto_now_add=True)
valid_ids_found = models.IntegerField(default=0)
How do I make the chart show the batch data historically from django and then output it to the chart?
I want to show the batches historically by date and also group by domain.
example of what the data to plot is like are :
www.someexample.com | 2022-09-03 | 34
www.someexample.com | 2022-09-04 | 55
First, you need to get the timestamps as date, together with the domain. Then you will need to sum up all the ID's right? (For each day)
To do that, you can get it from:
chartdata = ScanBatch.objects.all().values('timestamp__date','domain').annotate(models.Sum('valid_ids_found'))
Then pass that onto the template.
In the template, to prep the data you need to iterate over it in javascript. Like so:
const chartData = {{ chart_data |safe }};
let arr = [];
let arrlabels = [];
let domainlabels = [];
for (let value of Object.values(chartData)) {
arr.push(value.valid_ids_found__sum);
arrlabels.push(value.timestamp__date);
domainlabels.push(value.domain)
}
console.log(chartData)
Now you have your chart data prepped, ready to use in the chart.
const chartData = {{ chart_data |safe }};
let arr = []
let arrlabels = []
for (let value of Object.values(chartData)) {
arr.push(value.valid_ids_found__sum);
arrlabels.push(value.timestamp__date);
}
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: arrlabels ,
datasets: arr
},
options: {
scales: {
yAxes: [{
id: 'A',
type: 'linear',
position: 'left',
}, {
id: 'B',
type: 'linear',
position: 'right',
ticks: {
max: 1,
min: 0
}
}]
}
}
});
This is the first part at least, I do not have enough knowledge of Chart.js to differentiate between domain also. Sorry bud. Might help you along though!