以下代码效果很好:
def jsonLiveLeaderboard(request):
data = StraightredFixture.objects.filter(fixturematchday=12)
json_data = serializers.serialize('json', data)
return HttpResponse(json_data, content_type='application/json')
但是,如果我尝试使用类似的自制查询:
def jsonLiveLeaderboard(request):
cursor = connection.cursor()
cursor.execute(
"""
select username as User, floor((count(Goals)/2)-(if(sum(Loss)>0,1,0))) as Round, sum(Win) as Wins, sum(Goals) as Goals, sum(Loss) as Losses from
(select u.username as username, s.campaignno as campaign, if(f.hometeamscore>f.awayteamscore,1,0) as Win, if(f.hometeamscore<f.awayteamscore,1,0) as Loss, f.hometeamscore as Goals from straightred_fixture f, straightred_userselection s, auth_user u where s.fixtureid = f.fixtureid and s.teamselectionid = f.hometeamid and s.user_id = u.id union all
select u.username as username, s.campaignno as campaign, if(f.awayteamscore>f.hometeamscore,1,0) as Win, if(f.awayteamscore<f.hometeamscore,1,0) as Loss, f.awayteamscore as Goals from straightred_fixture f, straightred_userselection s, auth_user u where s.fixtureid = f.fixtureid and s.teamselectionid = f.awayteamid and s.user_id = u.id) t
group by username, campaign
having Losses = 0
order by Round DESC, Wins DESC, Goals DESC
""")
pointsCurrentSeasonLive = cursor.fetchmany(size=8)
json_data = serializers.serialize('json', pointsCurrentSeasonLive)
return HttpResponse(json_data, content_type='application/json')
我收到以下错误:
AttributeError at /jsonLiveLeaderboard/
'tuple' object has no attribute '_meta'
是否有一种简单的方法可以将“自制”查询转换为json,就像使用本机Django查询一样?
非常感谢,艾伦。
答案 0 :(得分:1)
serializers.serialize
专门用于Django查询集。你只有一个列表,所以你应该使用标准的json库:
json_data = json.dumps(pointsCurrentSeasonLive)