python - Django如何制作数据透视表?
问题描述
我无法为我的数据制作数据透视表。我从用户那里获取的数据是:司机姓名、日期、佣金、分支机构和其他一些数据,但这些是我想要制作数据透视表的数据。所以这里的模型将占据重要的领域。
模型.py
class InvoiceRegistering(models.Model):
driver_name = models.ForeignKey(Drivers, on_delete=models.SET(""), verbose_name="السائق")
pub_date = models.DateField('التاريخ') # default=timezone.now
the_car = models.ForeignKey(Cars, on_delete=models.SET(""), verbose_name="السيارة")
city = models.ForeignKey(Cities, on_delete=models.SET(""), verbose_name="المدينة")
branch = models.ForeignKey(Branches, on_delete=models.SET(""), verbose_name=" الفرع")
the_representer = models.ForeignKey(Representers, on_delete=models.SET(""), verbose_name="المندوب")
location = models.ForeignKey(Locations, on_delete=models.SET(""), verbose_name="اختر الموقع") # blank = True == required = False
sort_ofBox = models.ForeignKey(SortOfBoxes, on_delete=models.SET(""), verbose_name="اختر الصنف")
number_of_boxes = models.IntegerField(verbose_name="عدد الطبالي", default="")
sar_4box = models.IntegerField(verbose_name="ريال \ طبلية", default="")
receipt_num = models.IntegerField(verbose_name="رقم الايصال", default="")
def commision(self):
myvalue = ''.join(str(self.number_of_boxes * self.sar_4box))
return str(myvalue)
commision.short_description = "العمولة"
管理员.py
class InvoiceAdmin(ImportExportModelAdmin):
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
response = super(InvoiceAdmin, self).render_change_form(request, context, add, change, form_url, obj)
response.context_data['title'] = "تعديل" if response.context_data['object_id'] else "إضافة رد جديد"
return response
list_display = (
'id', 'driver_name', 'pub_date', 'the_car', 'the_representer', 'branch', 'location', 'number_of_boxes',
'sar_4box',
'commision', 'sort_ofBox', 'receipt_num')
list_filter = ('id', 'pub_date', 'driver_name', 'branch', 'the_car')
search_fields = (
'id', 'driver_name', 'pub_date', 'the_car', 'the_representer', 'branch', 'location', 'number_of_boxes',
'sar_4box',
'sort_ofBox', 'receipt_num')
我试图从模型中提取数据然后解析它,但事实证明它太复杂了。我通过模型内部的代码尝试了这一点:
def full_values(self):
fullValue = str(self.driver_name), str(self.pub_date), str(self.the_representer), str(self.the_car), str(self.city), str(self.location), str(self.sort_ofBox), self.number_of_boxes, self.sar_4box, self.receipt_num
return str(fullValue)
它返回所需的数据,问题是我不知道如何将它带到另一个模型或如何在表格中分析它。
我需要的是: 1- 如何制作一个计算所有佣金的数据透视表?列是分支,行是驱动程序。它会是这样的:
---+-----Branches
Drivers | D1 | R1 | T1
Noah | 62 | 23 | 52
Ahmad | 16 | 61 | 72
Saleh | 32 | 22 | 33
我在考虑熊猫数据透视表,然后在上下文中解析它并将其发送到页面,但我不知道该怎么做。
如果有人知道解决方案,请提供帮助。
解决方案
解决了!我使用 pandas 将 DataFrame 制作成数据透视表,然后通过上下文将其发送到我的模板。还通过用户编写的网址获取报告的年份。这是我的views.py:
from django.http import HttpResponse
import pandas as pd
from .models import InvoiceRegistering, Branches, gettingBranchesList
from django.shortcuts import render, redirect, get_object_or_404
import datetime
import django as dj
def YearlyReports(request, year): # month
qs = InvoiceRegistering.objects.filter(pub_date__year=year).values("driver_name", "amount", "branch")
data = pd.DataFrame(qs)
data = data.fillna(0)
data = data.rename(columns={'driver_name': 'السائق', 'branch': 'الفرع', 'amount': 'العمولة'})
pivot = pd.pivot_table(data, index='السائق', columns='الفرع', values='العمولة', aggfunc='sum',
margins=True, margins_name='الاجمالي', fill_value=0)
Date = "عمولة الطبالي للسائقين على حسب الفرع عن سنة {}".format(year)
context = {'YearsTable': pivot.to_html,
'description': Date,
}
return render(request, 'YearlyReports.html', context)
urls.py:
path("reports/yearlyreports/<int:year>/", views.YearlyReports, name="YearlyReports"),
推荐阅读
- business-intelligence - 许多公司默认流程的默认维度/事实表/列
- jquery - 如何保持for循环直到延迟对象被解决
- c++ - `ThreadPool` 的 C++ 实现无法按预期工作
- node.js - Hyperledger Fabric 版本 2:如何使用 Fabric Node SDK 2.2 查询 Block Header,例如数据哈希、先前哈希
- typo3 - TYPO3 前端错误:#1476045117 和 TYPO3 前端错误:#1580056272
- php - 无法加载动态库“curl.so”
- jupyter-notebook - SageMaker 在尝试添加生命周期配置以在重启后保持自定义环境持续时失败
- reactjs - 当变量值改变时重新渲染 ReactDom
- .net-core - .NET Core 31 - 单个 EXE - 要执行的应用程序不存在
- javascript - 组件“H”的视图配置 getter 回调必须是一个函数(收到未定义)