Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda