简体   繁体   English

select 数据以分钟为单位的时间间隔 django orm

[英]select data in a time interval in minutes django orm

How are you?你好吗? I need some help please.我需要一些帮助。 I am working in Django and I need to make a query of all sales between 00:00 and 00:30 minutes, so every 30 minutes I need to see the sales.我在 Django 工作,我需要查询 00:00 到 00:30 分钟之间的所有销售额,因此我需要每隔 30 分钟查看一次销售额。 I was putting together something like this but it is not working.我正在整理这样的东西,但它不起作用。

sales = (
    SalesOrder
    .objects
    .annotate(Sum('subtotal'))
    .filter(created_at__time__range= ('00:00:00:00', ''))
    .filter(created_at__time = hour_now)
)

This is a SQL query that delivers the correct data.这是一个提供正确数据的 SQL 查询。

SELECT sum(subtotal) as tot 
  FROM sales_salesorder ss 
 where extract(minute from created_at::time) between 31 and 59 and
       created_at::date = now()::date and 
       extract(hour from created_at) = extract(hour from CURRENT_TIME);

The problem is that I can't leave the sql query because I have to pass it through a for loop to return the data, that's why the most effective way is to use the ORM, that's the reason of my question.问题是我不能离开 sql 查询,因为我必须通过一个 for 循环来返回数据,这就是为什么最有效的方法是使用 ORM,这就是我提出问题的原因。

The direct translation from your sql to django query is:从 sql 到 django 查询的直接翻译是:

from django.utils import timezone

sales = (
    SalesOrder
    .objects
    .filter(created_at__minute__range=(31, 59))
    .filter(created_at__hour=timezone.now().hour)
    .filter(created_at__date=timezone.now().today())
    .count()
)

But, perhaps, a more elegant and index friendly approach is:但是,也许,更优雅和索引友好的方法是:

from django.utils import timezone
from datetime import datetime, timedelta

today = datetime.now().today()

date_from = timezone.datetime(
    today.year, today.month, today.day,
    0, 0, 0,
    tzinfo=timezone.get_current_timezone())

date_to = date_from + timedelta(minutes=30)

sales = (
    SalesOrder
    .objects
    .filter(created_at__range=(date_from, date_to))
    .count()
)

If you are looking to group by each half hour here a good answer: https://stackoverflow.com/a/61747028/842935如果您希望每半小时分组一次,这里有一个很好的答案: https://stackoverflow.com/a/61747028/842935

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM