ChartJS 在Django中使用charj构建图表

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

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

in views.py

def home(request):
    if request.user.is_authenticated:
        customers = User.objects.filter(groups__name='Customer').count()
        totalinvoice = invoice.objects.all().count()
        supplier = User.objects.filter(is_staff=True).count()

        # chart
        labels = ["Jan","Feb","Mar","Apr","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
        data = [12,14,19,25,28,80,23,35,46,78,45,23] // This data's should be retrieved dynamically

        return render(request, 'home.html', {
            'totalinvoices':totalinvoice,
            'customers':customers,
            'supplier':supplier,
            "labels":json.dumps(labels),
            "data":json.dumps(data),
        })
    else:
        return redirect("login")

请有人帮我弄清楚。

du7egjpx

du7egjpx1#

尝试

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:我用来测试查询集的示例模型。


# models.py

class invoice(models.Model):
    invoice_date = models.DateField()

测试


# python3 manage.py shell

# Step 1: create some random invoices

from django.utils import timezone
from .models import invoice
import random

random.seed(0) # be reproducible

date_0 = timezone.localdate().replace(2022, 1, 1)
a_day = timezone.timedelta(days=1)

for i in range(1000):
    rand_date = date_0 + random.randint(0, 364) * a_day
    invoice(invoice_date=rand_date).save()

# Step 2. Run the queryset.

data = invoice.objects\
    .values('invoice_date__month')\
    .annotate(month_wise_count=Count('id'))\
    .order_by('invoice_date__month')

for datum in data:
    print(f"{datum['invoice_date__month']:2}. {datum['month_wise_count']}")

这将生成以下结果:

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

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

相关问题