django serialize制作自定义显示格式

时间:2015-01-27 11:01:17

标签: python django django-serializer

这是我的代码:

for i in Showtime.objects.filter(movie_id=movieid,theater_id=theaterid,movietime__gte=get_today()):
    if i.mvtype not in movietimes:
        movietimes[i.mvtype] = []
    movietimes[i.mvtype].append({i.movietime.strftime('%Y-%m-%d') : i.movietime.strftime('%Y-%m-%dT%H:%M:%S.%fZ')})

结果是:

"3D": [ 
    {
        "2015-01-29": "2015-01-29T01:20:00.000000Z"
    }, 
    {
        "2015-01-29": "2015-01-29T03:10:00.000000Z"
    }, 
    {
        "2015-01-29": "2015-01-29T05:10:00.000000Z"
    }, 

    {
        "2015-01-28": "2015-01-28T17:10:00.000000Z"
    }, 
    {
        "2015-01-28": "2015-01-28T01:20:00.000000Z"
    }, 
]

但我想要的是:

"3D": [ 
    {
        "2015-01-29": {
                    "2015-01-29T01:20:00.000000Z",
                    "2015-01-29T03:10:00.000000Z"
                    "2015-01-29T05:10:00.000000Z"
        }, 

        "2015-01-28": {
                    "2015-01-28T17:10:00.000000Z"
                    "2015-01-28T01:20:00.000000Z"
        }, 
    }   
]    

我该怎么做呢 请帮帮我

1 个答案:

答案 0 :(得分:0)

以下代码:

for i in Showtime.objects.filter(movie_id=movieid,theater_id=theaterid,movietime__gte=get_today()):
    if i.mvtype not in movietimes:
        movietimes[i.mvtype] = {}
    dt = i.movietime.strftime('%Y-%m-%d')
    if dt not in movietimes[i.mvtype]:
        movietimes[i.mvtype][dt] = []
    movietimes[i.mvtype][dt].append(i.movietime.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))

会给你这样的东西:

"3D": {
        "2015-01-29": [
                    "2015-01-29T01:20:00.000000Z",
                    "2015-01-29T03:10:00.000000Z"
                    "2015-01-29T05:10:00.000000Z"
        ], 

        "2015-01-28": [
                    "2015-01-28T17:10:00.000000Z",
                    "2015-01-28T01:20:00.000000Z"
        ], 
    }