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

0👍

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,
            }
        ],          
    }
)

Leave a comment