Django ORM:将聚合查询集链接成一个

发布于 2024-08-05 17:22:49 字数 488 浏览 2 评论 0原文

我可以将这两个查询集链接成一个吗?

qs1 = OrderTicket.objects.filter(date__gt=datetime.date(2009, 1, 1), date__lt=datetime.date(2009, 1, 30)).values('order_type').annotate(value_1 = Sum('gbp_value')).order_by('order_type'),
qs2 = OrderTicket.objects.filter(date__gt=datetime.date(2009, 2, 1), date__lt=datetime.date(2009, 2, 30)).values('order_type').annotate(value_2 = Sum('gbp_value')).order_by('order_type'),

我想要的只是 value_1 和 value_2 列。 Q 对象不是我需要的。也许 ORM 不支持这一点。

Can I chain these two querysets into one?

qs1 = OrderTicket.objects.filter(date__gt=datetime.date(2009, 1, 1), date__lt=datetime.date(2009, 1, 30)).values('order_type').annotate(value_1 = Sum('gbp_value')).order_by('order_type'),
qs2 = OrderTicket.objects.filter(date__gt=datetime.date(2009, 2, 1), date__lt=datetime.date(2009, 2, 30)).values('order_type').annotate(value_2 = Sum('gbp_value')).order_by('order_type'),

All I want is the value_1 and value_2 columns. Q objects are not what I need. Maybe the ORM does not support this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回忆追雨的时光 2024-08-12 17:22:49

您可以使用 | 组合查询集和&运算符:

# You can combine queries with & and |.
>>> s1 = Article.objects.filter(id__exact=1)
>>> s2 = Article.objects.filter(id__exact=2)
>>> s1 | s2
[<Article: Area woman programs in Python>, <Article: Second article>]
>>> s1 & s2
[]

来源 http://www.djangoproject.com/documentation/models/basic/

You can combine querysets using the | and & operators:

# You can combine queries with & and |.
>>> s1 = Article.objects.filter(id__exact=1)
>>> s2 = Article.objects.filter(id__exact=2)
>>> s1 | s2
[<Article: Area woman programs in Python>, <Article: Second article>]
>>> s1 & s2
[]

Source http://www.djangoproject.com/documentation/models/basic/

智商已欠费 2024-08-12 17:22:49

我建议使用 Q 对象< /a> 替换 date__gt 和 date__lt 的过滤器

示例(未测试):

qs1 = OrderTicket.objects
    .filter(  Q(date__gt=datetime.date(2009, 1, 1), date__lt=datetime.date(2009, 1, 30)) 
            | Q(date__gt=datetime.date(2009, 2, 1), date__lt=datetime.date(2009, 2, 30))
           )
    .values('order_type').annotate(value_1 = Sum('gbp_value')).order_by('order_type')

这应该返回您要查找的两个日期。

I would suggest using Q objects to replace your filter for date__gt and date__lt

Example (not tested):

qs1 = OrderTicket.objects
    .filter(  Q(date__gt=datetime.date(2009, 1, 1), date__lt=datetime.date(2009, 1, 30)) 
            | Q(date__gt=datetime.date(2009, 2, 1), date__lt=datetime.date(2009, 2, 30))
           )
    .values('order_type').annotate(value_1 = Sum('gbp_value')).order_by('order_type')

This should return both the dates you are looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文