Reputation: 961
The following code works nicely:
def jsonLiveLeaderboard(request):
data = StraightredFixture.objects.filter(fixturematchday=12)
json_data = serializers.serialize('json', data)
return HttpResponse(json_data, content_type='application/json')
However, if I try to do the same with a homemade query like so:
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')
I get the following error:
AttributeError at /jsonLiveLeaderboard/
'tuple' object has no attribute '_meta'
Is there an easy way to convert a "homemade" query to json in much the same way you can with a native Django query?
Many thanks in advance, Alan.
Upvotes: 0
Views: 46
Reputation: 599490
serializers.serialize
is specifically for Django querysets. You just have a list, so you should use the standard json library:
json_data = json.dumps(pointsCurrentSeasonLive)
Upvotes: 1