django group通过聚合在不同的选择领域

时间:2017-02-12 06:33:48

标签: django django-orm

我有下表,

Account(models.Model):
    name = models.CharField(max_length=60)
    account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=30)


Ledger(models.Model):
    account = models.ForeignKey(Account, related_name='ledger')
    balance = models.DecimalField(max_digits=15, decimal_places=4, default=0.00)
    balance_date = models.DateField(default=datetime.date.today)

提到,帐户类型是,

ACCOUNT_TYPE = (
(0, 'Asset'),
(1, 'Liabilities'),
(2, 'Equity'),
(3, 'Income'),
(4, 'Expense')
)

例如,

Ledger 模型中,数据存储如下,

Account Name    Account Type   balance
------------    -------------  -------
sales           Income         400
Home expense    Expense        300
gross income    Income         100
staff salary    Expense        700
sales revenue   Income         300
Electric Bill   Expense        900

我希望在日期范围内分别获得所有IncomeExpense类型帐户的总余额。

要做到这一点,我已经做了以下琐事,

if request.method == 'GET':

    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')
    accounts = Account.objects.filter(Q(account_type=3) | Q(account_type=4))

    income = Ledger.objects.filter(
        account__in=accounts,
        balance_date__gte=start_date,
        balance_date__lte=end_date
    ).aggregate(Sum('balance'))

    serializer = LedgerSerializer(income, many=True)
    print serializer.data

    return Response(serializer.data})

但它返回空订单,我保证我在传递的日期范围内有数据,如果我从上面的查询中删除aggregation部分,则返回全部IncomeExpense数据没有总余额,这是合乎逻辑的,但当我添加aggregation部分时,其返回

[OrderDict()]

我在django orm中比较新。

1 个答案:

答案 0 :(得分:0)

您当前代码的问题在于此查询

> df <- add_flags(d)
Launching API request... done.
Parsing output... done.

=== SUMMARY ===
 records parsed
0 records with coordinates (0 valid)
0 records with country (0 valid)
0 records with scientific name
=== GEOSPATIAL ===
Warning message:
In gq_parse(req) :
  Something went wrong with the call. Got status 500: <html>
  <head>
    <title>Internal Server Error</title>
    <style>
      body {
        padding: 20px;
        font-family: arial, sans-serif;
        font-size: 14px;
      }
      pre {
        background: #F2F2F2;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <h1>Internal Server Error</h1>
    <p>The server has either erred or is incapable of performing
    the requested operation.</p>
    <pre>Traceback (most recent call last):
  File &quot;/base/data/home/runtimes/python27_experiment/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py&quot;, line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File &quot;/base/data/home/runtimes/python27_experiment/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py&quot;, line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File &quot;/base/data/home/runtimes/python27_experiment/python27_lib/versions/third_party/w [... truncated]

不返回查询集,但是您尝试序列化的字典。也许你可以先得到像这样的查询

income = Ledger.objects.filter(
    account__in=accounts,
    balance_date__gte=start_date,
    balance_date__lte=end_date
).aggregate(Sum('balance'))

然后你序列化

income = Ledger.objects.filter( account__in=accounts, balance_date__gte=start_date, balance_date__lte=end_date )

最后调用聚合方法

serializer = LedgerSerializer(income, many=True)

您需要的最后一件事是在您的回复中返回两个变量(例如在词典中)