django查询的月份值
我有这样的注释:它显示了一个字段的一个月
bar = Foo.objects.annotate(
item_count=Count('item')
).order_by('-item_month', '-item_year')
,这会产生这样的输出: html渲染
我想显示与上个月的item_count的item_count的变化月(第一个月除外)。如何使用注释来实现这一目标,还是需要使用大熊猫?
谢谢
编辑: 在sql中,这与滞后函数变得容易,它类似于
SELECT item_month, item_year, COUNT(item),
LAG(COUNT(item)) OVER (ORDER BY item_month, item_year)
FROM Foo
GROUP BY item_month, item_year
(ps:item_month和item_year是日期字段)
django orm是否与sql中的滞后相似?
I have an annotation like this: which displays the month wise count of a field
bar = Foo.objects.annotate(
item_count=Count('item')
).order_by('-item_month', '-item_year')
and this produces output like this:
html render
I would like to show the change in item_count when compared with the previous month item_count for each month (except the first month). How could I achieve this using annotations or do I need to use pandas?
Thanks
Edit:
In SQL this becomes easy with LAG function, which is similar to
SELECT item_month, item_year, COUNT(item),
LAG(COUNT(item)) OVER (ORDER BY item_month, item_year)
FROM Foo
GROUP BY item_month, item_year
(PS: item_month and item_year are date fields)
Do Django ORM have similar to LAG in SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在django orm中使用窗口函数
作为滞后
对于这些类型的查询, lag“ rel =“ nofollow noreferrer”> https://docs.djangoproject.com/en/4.0/ref/models/database-functions/#lag
ORM中的工作查询将看起来像这样:
#models.py.py.py.py.py
这只是一个虚拟表,向您显示
lag
和window
函数的用例因为Django文档上的滞后功能不可用。
查询看起来也将看起来
像您不想在提取的日期上订购_BY,则可以使用
f
表达式以下查询:
For these types of Query you need to use Window functions in django Orm
For Lag you can take the help of
https://docs.djangoproject.com/en/4.0/ref/models/database-functions/#lag
Working Query in Orm will look like this :
#models.py
This is just a dummy table to show you the use case of
Lag
andWindow
function in djangoBecause examples are not available for Lag function on Django Docs.
Query will look like
Also if you don't want to order_by on extracted year of date then you can use
F
expressions like thisQuery for this :