django - 从 Django 中的两个表中计算发票应用程序的总值
问题描述
我正在尝试创建一个将从相关表生成数据的发票,但我不确定如何继续。本质上,一个Invoice
实例应该捕获在模型中找到的记录小时数Timesheet
并乘以在另一个表中找到的速率(ProjectUser
)我附上了数据库模式的样子:https ://dbdiagram.io/d/5ef0e2bc9ea313663b3ae6e4
如何amount
使用来自ProjectUser
(user_hour_cost) 和Timesheet
( day_1
through day_7
) 的数据填充 Invoice ModelForm 上的字段。
说user_hour_cost
是 500,day_1
通过值的总和day_7
是 50。如何在发票表单上显示金额值25000
?(500 * 50)。
解决方案
如果我理解你想要做什么,这样的事情会起作用吗?:
cost_data = []
grand_total = 0.00
for user_timesheet in Timesheet.objects.filter(week=1).all(): # or whatever date range you want, etc.
# you can optimize this by joining the Timesheet and ProjectUser queries as an alternative
project_user = ProjectUser.objects.get(user=user_timesheet.user)
rate = project_user.user_hour_cost
user_total = 0.00
user_data = { 'user': project_user.user }
# loop over the 7-day range
for i in range(1,7):
day_key = f"day_{str(i)}"
user_data[day_key] = decimal(user_timesheet.get_day_hours(i) * rate)
user_total += decimal(user_timesheet.get_day_hours(i) * rate)
user_data['total'] = user_total
cost_data.append(user_data)
grand_total += user_data['total']
user_data = {} # clear it just to be safe
context = { 'cost_data': cost_data, 'grand_total': grand_total }
return render(request, 'template.html', context)
这会将所有内容放入一个字典数组中,您可以将其传递给模板并根据需要进行迭代以显示“总计”元素或每日总计,例如:
{% for user_data in cost_data %}
Username: {{ user_data.user.username }} //accessing the User object
Person Total: {{ user_data.total }} //the total amount for this person
Day 1: {{ user_data.day_1 }} //day 1 total
Day 2: {{ user_data.day_2 }} //day 2 total
...
Day 7: {{ user_data.day_7 }} //day 7 total
{% endfor %}
Invoice Total: {{ grand_total }} //total for the whole invoice
最后,您将需要在 Timesheet 模型中使用一个方法,以使此特定代码能够像这样工作:
class Timesheet(models.Model):
...
...
def get_day_hours(self, day):
# there are other ways to do this as well, this was just the easiest for right now
if day == 1:
return self.day_1
elif day == 2:
return self.day_2
...
elif day == 7:
return self.day_7
这本质上是伪代码,不知道你拥有的实际代码,而且有点粗糙(有可能用更少的 python 代码在数据库中执行这一切)。可能还有其他更有效的方法来实现这一点,但这是我想到的。
推荐阅读
- java - Firestore 讲座操作计数
- python - 将长列表与数据框中的字符串进行比较,并在匹配的基础上填充 Python 中的数据框
- java - Recyclerview 没有第一次加载( Firebase )
- reactjs - React JS,显示来自嵌套 json 的数据
- javascript - 是否可以使用javascript获取屏幕颜色?
- c++ - Linux - 信号:错误:非静态成员函数的使用无效
- sql-server - SQL Server + Linux + VB6 + Wine + Adodb.Recordset +错误 430
- c++ - CMake链接错误,找到库但“未定义的引用”
- c++ - 为什么 C++11 中捕获的变量在捕获中具有不同的值?
- docker - Docker Toolbox 拒绝在浏览器上连接 - 尝试了不同的解决方案 - Windows 7