python - Django - 使用不常见的字段数据压缩多个查询集

标签 python django django-queryset

我有一个模型,我可以在其中获取 published count , under process count , rejected count , received count按月计算

class PreData(models.Model):

    status=models.CharField(max_length=200,default=None,null=True)

    receivedon=models.DateField(default=None,blank=False,null=True)

    publishedon = models.DateField(default=None, blank=True, null=True)

received count基于每月计数 receivedon DateField在模型中,published count基于每月计数 publishedon DateField在模型中,rejected countunder process count基于特定 status 的计数CharField 的值在模型中。

写完下面的查询后我很挣扎,我对如何获取数据来填充列一无所知(见图)。我不确定我写的查询是否有帮助。

当我想要压缩 received_monthly_data 时,问题就出现了。和published_monthly_data但是received_monthly_data有四月份的数据和 published_monthly_data没有四月。当我压缩时,结果将在四月发布。我不知道该怎么做。

received_monthly_data = PreData.objects.filter(journaluser=request.user.username).\
                annotate(month=TruncMonth('receivedon'),year=TruncYear('receivedon')).values('month','year').\
                annotate(c=Count('id')).order_by('-month')

published_monthly_data = PreData.objects.filter(Q(journaluser=request.user.username)&~Q(pdfsenton=None)). \
                annotate(month=TruncMonth('publishedon'), year=TruncYear('publishedon')).values('month', 'year'). \
                annotate(c=Count('id')).order_by('-month')


underproc_data= PreData.objects.filter(Q(journaluser=request.user.username)&~Q(status="[Published]"))

I need the data to fill these columns

非常感谢任何帮助。

最佳答案

也许您可以使用 itertools.zip_longest 来压缩最长的序列,并用 None 替换较短序列中的缺失值。这样您就不会丢失四月份的数据。

如果您希望使用 None 以外的值,请指定 fillvalue 参数。

来自https://docs.python.org/3/library/itertools.html#itertools.zip_longest

itertools.zip_longest(*iterables, fillvalue=None)

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.

请注意,该函数在 Python 2 中称为 itertools.izip_longest

关于python - Django - 使用不常见的字段数据压缩多个查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49977258/

相关文章:

python - 尝试使用 for 循环比较文本

python - 重复列表中的每个元素任意次

python - 使用 django 的 Web 服务器 ini 文件编辑器

django - 如何在 Django 中限制静态文件上传的用户?

django - 从 Django 查询集中获取第一个对象

具有反向外键过滤功能的 Django Queryset

python - 如何在 Python 中使用 argparse 为一个参数设置可变数量的参数?

python - 用Python(库)读取多媒体播放列表文件

python - 尝试获取枚举样式选择=适用于 django 但整个连音出现在下拉列表中

django - 与 F 表达式的时间差 : error