Python Django-在执行分组后如何组合两个查询
目标:按项目分组所有输入和输出,然后将数量相加,在我的模板中生成一个简单的表格,如下所示:Python Django-在执行分组后如何组合两个查询,python,django,Python,Django,目标:按项目分组所有输入和输出,然后将数量相加,在我的模板中生成一个简单的表格,如下所示: Item | Total In | Total Out| Stock 1. Cement | 400 | 300 | 100 我的模特 class Incoming(models.Model): ... project_site = models.ForeignKey(ProjectSite, related_name='in_project_sit
Item | Total In | Total Out| Stock
1. Cement | 400 | 300 | 100
我的模特
class Incoming(models.Model):
...
project_site = models.ForeignKey(ProjectSite, related_name='in_project_site', default=7, null=True, on_delete = models.SET_NULL)
item = models.ForeignKey(Item, related_name='item_in', null=True, on_delete = models.SET_NULL)
quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0)
...
class Outgoing(models.Model):
...
base_in = models.ForeignKey('warehouse.Incoming', related_name='out', on_delete = models.SET_NULL, null=True)
quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0)
...
好的,我们的目标是按项对所有传入项进行分组,然后注释当前传入和传出的总数。所以我很自然地在我的观点中这样做了
incoming = Incoming.objects.filter(project_site__id=self.object.id)
context['inventory'] = incoming.values('item__item_name')\
.annotate(tot_in=Sum('quantity'))\
.annotate(tot_out=Sum('out__quantity'))
这并没有给出正确的总数,现在经过一些搜索,这显然是一个问题。我发现的一个建议是将查询分为to,这就是我所做的
context['current_in'] = incoming.values('item__item_name').annotate(tot_in=Sum('quantity'))
context['current_out'] = incoming.values('item__item_name').annotate(tot_out=Sum('out__quantity'))
这为每个输入和输出提供了正确的总和,现在我的问题是如何再次合并/组合这两者,以便在模板上轻松循环?我做了一次搜索,尝试了以下方法,但没有成功
list(chain(pagelist1, pagelist2))
# This does not combine items with same ITEM name. The output for this is
Item | Total In | Total Out| Stock
Cement | 400 | |
Cement | | 300 |
组建工会也无济于事。任何帮助都行。这个怎么样:
incoming.values('item__item_name').annotate(tot_in=Sum('quantity'), tot_out=Sum('out__quantity'))
如果它不起作用,那么您可以在这里使用pythonic方法,使用:
您的第一个建议在链接注释时提供相同的输出。与我的第一个查询相同。您的第二个建议为我提供了正确的总和,但由于某种原因,当我尝试在模板上循环它时,它似乎是水平而不是向下填充我的表。我们如何将其格式化为查询集,以便我可以做更多的事情,如过滤?谢谢,这解决了我的问题,你们怎么知道这些库?我想我还有很多东西要学。当你把东西放到zip中时,它会变成一个生成器,迭代它就会变成一个列表。您可以在这里运行,但不能在这里运行django筛选器。
from itertools import zip_longest
current_in = incoming.values('item__item_name').annotate(tot_in=Sum('quantity'))
current_out = incoming.values('item__item_name').annotate(tot_out=Sum('out__quantity'))
context['current'] = [{**u, **v} for u, v in zip_longest(current_in, current_out, fillvalue={})]