Django - 日期时间列之间的差异总和

发布于 2024-12-04 23:19:10 字数 599 浏览 0 评论 0原文

我有记录first_action 和last_action 日期时间列的UserSession 模型, 我想知道用户在应用程序中花费了多长时间 - 这是两者之间的差异之和(忽略那些带有 Null last_action 的内容)。

不幸的是,django ORM 聚合函数仅适用于单个列,因此为了提高效率(每个用户可以有数千个会话),我用原始 SQL 编写了它,但因为我得到了一些很高的数字,所以我将其与 python 求和进行比较。不知道为什么,两次计算的结果不一样,你能帮我解决一下吗?

Python:

sum(((us.last_action - us.first_action) for us in UserSession.objects.filter(user_id=1234) if us.last_action), datetime.timedelta(0))

SQL:

select sum(last_action - first_action) as total_time   from usersession where user_id = 1234 and last_action is not null;

I have UserSession models that record first_action and last_action datetime columns,
I want to know how long a user spent in the app - that is the sum of the difference between the two (ignoring those with Null last_action).

Unfortunately django ORM aggregate functions only work on a single column, so for the sake of efficiency (there can be thousands of sessions per user) I wrote it in raw SQL, but because I got some high numbers I compared to a python sum. I don't know why, but the two calculations do not show the same result, can you help me figure it out?

Python:

sum(((us.last_action - us.first_action) for us in UserSession.objects.filter(user_id=1234) if us.last_action), datetime.timedelta(0))

SQL:

select sum(last_action - first_action) as total_time   from usersession where user_id = 1234 and last_action is not null;

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

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

发布评论

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

评论(1

酒儿 2024-12-11 23:19:10

我发现了问题 - 我不知道在 mysql 中从一个日期时间减去另一个日期时间会做什么,但这不是我想要的。

正确的 SQL 查询是:

select sum(timestampdiff(SECOND, first_action, last_action )) as total_time  from usersession where user_id = 123 and last_action is not null

现在 sql 结果与 python 结果相同 - 无需将所有会话拉入内存。

I found the problem - I don't know what subtracting one datetime from another does in mysql, but it wasn't what I wanted.

The correct SQL query is:

select sum(timestampdiff(SECOND, first_action, last_action )) as total_time  from usersession where user_id = 123 and last_action is not null

now the sql result is the same as the python result - without pulling all the sessions to memory.

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