Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
How to display django models with datetime field in chart using chartjs?

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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:

Added domain

Edit start

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)

Edit end

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!

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda