'How to filter and add multiple datasets using Django and Chart.js

I've been scratching my head for quite a while on this so any help is much appreciated.

Let's say I have a model called Transaction.

class Transaction(models.Model):
    time = models.DateTimeField(auto_now_add=True, blank=True)
    client = models.ForeignKey(User , on_delete=models.Cascade)
    value = models.IntegerField()

I want to generate a chart using chart.js. So far i am able to do this for all the objects using this JS:

<script>
 $(function () {
var $xChart = $("#xChart");
$.ajax({
  url: $xChart.data("url"),
  success: function (data) {
    var ctx = $xChart[0].getContext("2d");
    new Chart(ctx, {
      type: 'line',
      data: data,
      options: {
        responsive: true,
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: 'xChart'
        }
      }
    });

  }
});
  });

</script>

And this FBV for the ajax call:

def x_chart(request):
  def random_color():
    return "#"+''.join([choice('ABCDEF0123456789') for i in range(6)])
  labels=[]
  data=[]
  enddate = datetime.now()
  startdate = datetime.now().date() - relativedelta(days=3)

  transactions = Transaction.objects.filter(time__range=[startdate,enddate])

  grouped_transactions = transactions.values("time__day").annotate(total=Sum('value'))
  for key in grouped_transactions:
    labels.append(key['time__day'])
    data.append(key['total'])    
    
  return JsonResponse(
    data={
        'labels': labels,
        'datasets': [
            {
          'label': 'All Transactions,
          'backgroundColor': str(random_color()),
          'data': data,
            }
        ],          
    }
)

I want to create a dataset from each Transaction.client field and then pass it as Json to the ajax request. How would i be able to do that since the lables are the dates and some clients don't have transactions in certain dates but some do. Thanks



Solution 1:[1]

You need to specify the user in your filter. Use request.user.

def x_chart(request):
  def random_color():
    return "#"+''.join([choice('ABCDEF0123456789') for i in range(6)])
  labels=[]
  data=[]
  enddate = datetime.now()
  startdate = datetime.now().date() - relativedelta(days=3)
  the_client = request.user
  transactions = Transaction.objects.filter(client=the_client,time__range=[startdate,enddate])

  grouped_transactions = transactions.values("time__day").annotate(total=Sum('value'))
  for key in grouped_transactions:
    labels.append(key['time__day'])
    data.append(key['total'])    
    
  return JsonResponse(
    data={
        'labels': labels,
        'datasets': [
            {
          'label': 'All Transactions,
          'backgroundColor': str(random_color()),
          'data': data,
            }
        ],          
    }
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 enes islam