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

时间:2018-04-23 09:10:23

标签: python django django-queryset

我有这个模型,我每个月都会抓取published countunder process countrejected countreceived 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_datapublished_monthly_data,但received_monthly_data包含4月份的数据而published_monthly_data没有4月份的数据。当我拉链时,结果将在4月份松动。我无法想象如何做到这一点。

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

也许您可以使用@Insert来压缩最长的序列,并将itertools.zip_longest替换为较短序列中的缺失值。这样你就不会失去4月份的数据。

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

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

  

itertools.zip_longest(* iterables,fillvalue = None)

     

创建一个聚合来自每个迭代的元素的迭代器。如果迭代的长度不均匀,则缺少值   用fillvalue填写。迭代持续到最长   迭代已经筋疲力尽。

请注意,该函数在Python 2中称为fillvalue