How can get obj between two date range for each da

2019-08-22 16:01发布

I have data in Postgres DataBase like this based on my Model Event

 | 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

I need to return response group_by date and If Event duration (end_date, start_date) took 2 days so i need return him twice in two days and this all should be order by date. So response should look like this:

    {
      "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",
        }]
     }

How can i do this?

2条回答
beautiful°
2楼-- · 2019-08-22 16:41

Your example data isn't a Django Model, its just a regular 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",
    },
]

You could simply iterate over it and build the required results 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)
查看更多
beautiful°
3楼-- · 2019-08-22 16:53

Ok. I find decision for this

1) First i find SQL that i need for this

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

2) Second i write this on Django ORM:

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

So i get list that i want:

[{
    "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"
}]

This response is nice for me.

查看更多
登录 后发表回答