如何为每个日期在两个日期范围之间获取obj

时间:2018-10-19 07:17:13

标签: sql django postgresql django-rest-framework django-queryset

基于我的模型事件

,我在Postgres数据库中拥有这样的数据
 | id |  name  |    start_date       |      end_date       |
   1    Event1  2018-09-14 14:22:00     2018-09-15 14:22:00
   2    Event2  2018-09-15 14:22:00     2018-09-15 15:22:00

我需要返回group_by日期,如果事件持续时间(结束日期,开始日期)花费了2天,那么我需要在两天内返回两次,所有这些都应该按日期排序。 因此响应应如下所示:

    {
      "2018-09-14": [
          {
            "id": 1,
            "name": "Event1",
            "start_date": "2018-09-14 14:22:00",
            "end_date": "2018-09-15 14:22:00",
        }],
        "2018-09-15": [{
            "id": 1,
            "name": "Event1",
            "start_date": "2018-09-14 14:22:00",
            "end_date": "2018-09-15 14:22:00",
        },
        {
            "id": 2,
            "name": "Event2",
            "start_date": "2018-09-15 14:22:00",
            "end_date": "2018-09-15 15:22:00",
        }]
     }

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您的示例数据不是Django模型,而是常规的Python dict

data = [
    {
        "id": 1,
        "name": "Event1",
        "start_date": "2018-09-14 14:22:00",
        "end_date": "2018-09-15 14:22:00",
    },
    {
        "id": 2,
        "name": "Event2",
        "start_date": "2018-09-15 14:22:00",
        "end_date": "2018-09-15 15:22:00",
    },
]

您可以简单地对其进行迭代并构建所需的结果dict

from collections import defaultdict

result = defaultdict(list)

for item in data:
    start_date = item['start_date'][:10]
    end_date = item['end_date'][:10]

    result[start_date].append(item)

    if start_date != end_date:
        result[end_date].append(item)

答案 1 :(得分:0)

好的。我为此决定了

1)首先,我找到了为此所需的SQL

"SELECT DISTINCT generate_series(start_date::date, end_date::date, '1 day'::interval) AS dates, * FROM api_event ORDER BY dates")

2)其次,我在Django ORM上编写了此代码:

Event.objects.annotate(dates=Func(F('start_date'), F('end_date'), Value('1 day'), function='generate_series')).all()

所以我得到了我想要的清单:

[{
    "id": 1,
    "name": "Event1",
    "dates": "2018-09-14",
    "start_date": "2018-09-14 14:22:00",
    "end_date": "2018-09-15 14:22:00"
}, {
    "id": 1,
    "name": "Event1",
    "dates": "2018-09-15",
    "start_date": "2018-09-14 14:22:00",
    "end_date": "2018-09-15 14:22:00"
}, {
    "id": 2,
    "name": "Event2",
    "dates": "2018-09-15",
    "start_date": "2018-09-15 14:22:00",
    "end_date": "2018-09-15 15:22:00"
}]

这个回复对我很好。