首页 > 解决方案 > 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 在父子层次结构中显示子节点累积值的最佳方法是什么?

标签: djangodjango-modelshierarchical-data

解决方案


推荐阅读