django - Django中父子层次结构的累计总和
问题描述
我想在 django 中创建成本层次结构,并在父子层次结构中显示父节点的累积值。我还想显示子节点值。
为此,我有以下模型:
class accounts(models.Model):
account_nr = models.IntegerField(null=True)
account_name = models.CharField(max_length=100)
parent_account_nr = models.IntegerField(null=True)
一个典型的账户列表是:
account_nr account_name parent_account_nr
1000 project 1 null
1010 subproject 1 1000
1011 task 1 1010
1012 task 2 1010
我有另一个模型,其中我将值添加为事务:
class transactions(models.Model):
transaction_id = models.CharField(max_length=100)
account_ID = models.ForeignKey(accounts, on_delete=models.CASCADE)
debit_value = models.DecimalField(max_digits=10, decimal_places=2)
credit_value = models.DecimalField(max_digits=10, decimal_places=2)
我目前有以下视图,它向我显示了事务模型的累积条目:
def home(request):
account_query = accounts.objects.all() \
.annotate(Sum('transactions__debit_value')) \
.annotate(Sum('transactions__credit_value')) \
.order_by('account_nr')
args = {'account_queryx': account_query}
return render(request, 'home.html', args)
使用以下模板,我可以查看模型中的累积条目。
{% extends "base.html" %}
{% block content %}
<table>
<tr>
<th>Account</th>
<th>Omschrijving</th>
<th>Debit</th>
<th>Credit</th>
</tr>
{% for account_query in account_queryx %}
<tr>
<td>{{ account_query.account_nr }}</td>
<td>{{ account_query.account_name }}</td>
<td>{{ account_query.transactions__debit_value__sum}}</td>
<td>{{ account_query.transactions__credit_value__sum }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
我无法理解的问题是:如何创建一个查询来显示成本层次结构中父节点的累积值?
我遇到了以下页面,它提供了一个带有递归 CTE 的 SQL 解决方案。https://sqlsunday.com/2014/04/06/accumulating-in-a-hierarchy/ 但是据我所知,这在 Django 中不起作用。
使用 Django 在父子层次结构中显示子节点累积值的最佳方法是什么?
解决方案
推荐阅读
- javascript - 无法加载通过 ember-auto-import 导入 css 的模块
- eclipse - 如何在 Eclipse 中为 OSGI 项目添加 2 个发布者?
- python - Python在系统关闭之前做些什么?
- mongodb - 从 MOngodb 中的嵌套数组中删除值
- mysql - 如何使用“MATCH ... AGAINST”和 GROUP_CONCAT 进行标签搜索
- vue.js - nuxt vuetify 给出 SassError: Expected identifier
- docker - 甚至可以将我的 docker-compose.yml 转换为 heroku.yml 吗?
- networking - 所有标记的 VLAN 的 Linux 接口,不包括未标记的流量
- google-sheets - 将城市和邮政编码与 G 表格中的列表匹配
- python - 如何编写一个接受数字作为参数并打印从 1 到最大值并用方括号括起来的每个数字的函数?