ChartJS 在Django中使用charj构建图表

bxgwgixi  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(223)

我需要用chartjs创建一个图表,在折线图中显示当前年份的月份计数。数据应该从名为“invoice”的模型中检索,字段名称为“Invoice_date”。
备注:Invoice_date是一个日期字段()。

  1. in views.py
  2. def home(request):
  3. if request.user.is_authenticated:
  4. customers = User.objects.filter(groups__name='Customer').count()
  5. totalinvoice = invoice.objects.all().count()
  6. supplier = User.objects.filter(is_staff=True).count()
  7. # chart
  8. labels = ["Jan","Feb","Mar","Apr","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
  9. data = [12,14,19,25,28,80,23,35,46,78,45,23] // This data's should be retrieved dynamically
  10. return render(request, 'home.html', {
  11. 'totalinvoices':totalinvoice,
  12. 'customers':customers,
  13. 'supplier':supplier,
  14. "labels":json.dumps(labels),
  15. "data":json.dumps(data),
  16. })
  17. else:
  18. return redirect("login")

请有人帮我弄清楚。

du7egjpx

du7egjpx1#

尝试

  1. data = invoice.objects.filter(invoice_date__year=2022).values('invoice_date__month').annotate(month_wise_count=Count('id')).order_by('invoice_date__month')

然后,在循环数据时,执行datum['month_wise_count'],或在模板{{ datum.month_wise_count }}中执行。
请注意,实际上不应使用.filter(invoice_date__year=2022)。请用表示当前年份的变量替换2022。
UPDATE:我用来测试查询集的示例模型。

  1. # models.py
  2. class invoice(models.Model):
  3. invoice_date = models.DateField()

测试

  1. # python3 manage.py shell
  2. # Step 1: create some random invoices
  3. from django.utils import timezone
  4. from .models import invoice
  5. import random
  6. random.seed(0) # be reproducible
  7. date_0 = timezone.localdate().replace(2022, 1, 1)
  8. a_day = timezone.timedelta(days=1)
  9. for i in range(1000):
  10. rand_date = date_0 + random.randint(0, 364) * a_day
  11. invoice(invoice_date=rand_date).save()
  12. # Step 2. Run the queryset.
  13. data = invoice.objects\
  14. .values('invoice_date__month')\
  15. .annotate(month_wise_count=Count('id'))\
  16. .order_by('invoice_date__month')
  17. for datum in data:
  18. print(f"{datum['invoice_date__month']:2}. {datum['month_wise_count']}")

这将生成以下结果:

  1. 1: 84
  2. 2: 89
  3. 3: 92
  4. 4: 78
  5. 5: 74
  6. 6: 79
  7. 7: 84
  8. 8: 92
  9. 9: 79
  10. 10: 70
  11. 11: 90
  12. 12: 89

道歉:我犯了一个错误,把.order_by放在.values之前,它应该在queryset的末尾,现在是正确的。

展开查看全部

相关问题