如何在Django中将查询转储到JSON

时间:2013-10-23 12:37:40

标签: python json django

我有把数据转储到json的问题,我使用下面的代码,我在这一行得到了例外

Result = json.dumps([{'jalaliDate': o.jalaliDate} for o in matchDays], cls=DjangoJSONEncoder)

MatchDays值为[{'jalaliDate': u'1392/07/30'}]

我认为我的过滤器中的values("jalaliDate")出现了问题,当我删除它时,每件事情都可以。

def calendar(request, year, month, day, hash):
    try:
        gregorianList = JalaliToGregorian(year, month, day).getGregorianList()
        startDate = datetime.date(gregorianList[0]-1,gregorianList[1],gregorianList[2])
        endDate = datetime.date(gregorianList[0]+1,gregorianList[1],gregorianList[2])
        matchDays = Match.objects.filter(matchDate__gt=startDate, matchDate__lt=endDate).values("jalaliDate").distinct()
        result = json.dumps([{'jalaliDate': o.jalaliDate} for o in matchDays], cls=DjangoJSONEncoder)
    except Exception:
        print Exception.message
    return result

这是在控制台上的响应

0 errors found
October 23, 2013 - 16:18:04
Django version 1.5.2, using settings 'topelevensdjango.settings'
Development server is running at 127.0.0.1:800
Quit the server with CTRL-BREAK.
<attribute 'message' of 'exceptions.BaseException' objects>
[23/Oct/2013 16:18:14] "POST /json/ HTTP/1.1" 500 723

这是网上的回复

>>> jsonrpc.calendar(1392, 1, 1, 22)
Requesting ->
{"id":"jsonrpc", "params":[1392, 1, 1, 22], "method":"calendar", "jsonrpc":"1.0"}
Deferred(128, unfired)
Error ->
STATUS: 500
[object Object]

1 个答案:

答案 0 :(得分:0)

最后我找到了答案 用于分组结果我使用了不正确的错误

我已经替换了这段代码

matchDays = Match.objects.filter(matchDate__gt=startDate, matchDate__lt=endDate).values("jalaliDate").distinct()

使用此代码

matchDays = Match.objects.filter(matchDate__gt=startDate, matchDate__lt=endDate)
matchDays.query.group_by = ['jalaliDate']

问题已经消失 再见