首页 > 解决方案 > 将数据附加到标签(Chart.js 和 Django 3)

问题描述

我得到了这个view,我得到了 3 种类型的数据,定义我的标签并相互添加 2 个字典,以在我的 chart.js 的一个栏中显示收集的费用金额。

在这种情况下,我在每个费用中只有一个对象,它是在 8 月创建的,但它显示为在 1 月创建的。

似乎我没有使用正确的标签附加创建对象的月份。

我怎样才能做到这一点?

class SalesExpensesChart(APIView):
    """
    View to list all sales and expenses.
​
    * Requires session authentication.
    * Only the users own data is visible to the user authenticated.
    """
    authentication_classes = [SessionAuthentication]
    permission_classes = []
​
    def get(self, request, format=None):
        user = Account.objects.get(email=request.user)
        invoices = user.invoice.all()
        expenses_to_pay = user.expenses_to_pay.all()
        expenses_paid = user.expenses_paid.all()
​
        # Get total earnings in the different months (month: 1-12)
        total_earn_month = {}
        for invoice in invoices:
            invoice_month = invoice.created_at.month
            if invoice_month in total_earn_month:
                total_earn_month[invoice_month] += invoice.total
            else:
                total_earn_month[invoice_month] = invoice.total
​
        # Get total expenses to pay in the different months (month: 1-12)
        total_etp_month = {}
        for expense in expenses_to_pay:
            etp_month = expense.invoice_date.month
            if etp_month in total_etp_month:
                total_etp_month[etp_month] = expense.price
            else:
                total_etp_month[etp_month] = expense.price
​
        # Get total expenses to pay in the different months (month: 1-12)
        total_ep_month = {}
        for expense in expenses_paid:
            ep_month = expense.purchase_date.month
            if ep_month in total_ep_month:
                total_ep_month[ep_month] += expense.price
            else:
                total_ep_month[ep_month] = expense.price
​
        total_expenses = {k: total_ep_month.get(k, 0) + total_etp_month.get(k, 0)
                          for k in set(total_ep_month.keys()) | set(total_etp_month.keys())}
​
        # Get labels
        labels = ['January',
                  'February',
                  'March',
                  'April',
                  'May',
                  'June',
                  'July',
                  'August',
                  'September',
                  'October',
                  'November',
                  'December']
​
        # Pack values to pass them to the template
        sales = total_earn_month.values()
​
        return Response({
            'labels': labels,
            'sales': sales,
            'total_expenses': total_expenses.values()
        })

标签: pythondjangochart.js

解决方案


所以我设法解决了它。

这里的区别在于,我们循环遍历月份,然后我们将它们设置为0,然后再循环检查不同月份是否有数据。这将返回0,当其中没有任何内容时,而不是将其排除在外,这将导致数据空间在下个月被占用。

这是最终结果:

from rest_framework.authentication import SessionAuthentication
from rest_framework.views import APIView
from rest_framework.response import Response

from accounts.models import Account


class SalesExpensesChart(APIView):
    """
    View to list all sales and expenses.

    * Requires session authentication.
    * Only the users own data is visible to the user authenticated.
    """
    authentication_classes = [SessionAuthentication]
    permission_classes = []

    def get(self, request, format=None):
        # Variables for object calls
        user = Account.objects.get(email=request.user)
        invoices = user.invoice.all()
        expenses_to_pay = user.expenses_to_pay.all()
        expenses_paid = user.expenses_paid.all()

        # Set all months to 0 - This is done to show them at the right label
        total_earn_month = {}
        total_etp_month = {}
        total_ep_month = {}
        for month in range(0, 12):
            total_earn_month[month] = 0
            total_etp_month[month] = 0
            total_ep_month[month] = 0

        # Get total earnings in the different months (month: 1-12)
        for invoice in invoices:
            invoice_month = invoice.created_at.month
            total_earn_month[invoice_month-1] += invoice.total

        # Get total expenses to pay in the different months (month: 1-12)
        for expense in expenses_to_pay:
            etp_month = expense.invoice_date.month
            total_etp_month[etp_month-1] += expense.price

        # Get total expenses to pay in the different months (month: 1-12)
        for expense in expenses_paid:
            ep_month = expense.purchase_date.month
            total_ep_month[ep_month-1] += expense.price

        # add the two dicts for the two different expenses to one dict
        total_expenses = {k: total_ep_month.get(k, 0) + total_etp_month.get(k, 0)
                          for k in set(total_ep_month.keys()) | set(total_etp_month.keys())}

        # Get labels
        labels = ['January',
                  'February',
                  'March',
                  'April',
                  'May',
                  'June',
                  'July',
                  'August',
                  'September',
                  'October',
                  'November',
                  'December']

        # Pack values to pass them to the template
        sales = total_earn_month.values()
        print(total_ep_month)

        return Response({
            'labels': labels,
            'sales': sales,
            'total_expenses': total_expenses.values()
        })

推荐阅读