Commit bfa63873 authored by Hubert Denkmair's avatar Hubert Denkmair

fix 500, use django orm

parent 3c81c363
from django.shortcuts import render
from django.db.models import F, Max, ExpressionWrapper, FloatField
from django.db.models.query import RawQuerySet
from core.models import SnakeGame
from django.db.models.expressions import RawSQL
from django.db import models
def sattr(obj, attr, val):
if isinstance(obj, dict):
......@@ -19,9 +18,8 @@ def gattr(obj, attr):
def table(request, data, usr, title, rotate):
i = 0
for d in data:
sattr(d, 'position', '{}.'.format(i+1))
sattr(d, 'position', '{}.'.format(i+1))
if request.user.is_authenticated and gattr(d, 'user__username') == request.user.username:
sattr(usr, 'position', gattr(d, 'position'))
i = i + 1
......@@ -54,42 +52,15 @@ def maxage(request):
return table(request, data, usr, 'Max Age', 'highscore_consumerate')
def consumerate(request):
data = SnakeGame.objects.raw(
'''SELECT 1 as "id", "auth_user"."username" as "user__username",
max(
(natural_food_consumed + carrison_food_consumed + hunted_food_consumed)
/
(end_frame - start_frame)
) AS "score"
FROM "core_snakegame" LEFT OUTER JOIN "auth_user"
ON ("core_snakegame"."user_id" = "auth_user"."id")
GROUP BY "auth_user"."username"
ORDER BY
(natural_food_consumed + carrison_food_consumed + hunted_food_consumed)
/
(end_frame - start_frame) DESC
''')
data = SnakeGame.objects.values('user__username').annotate(
score=Max(ExpressionWrapper(
(F('natural_food_consumed') + F('carrison_food_consumed') + F('hunted_food_consumed'))
/ (F('end_frame') - F('start_frame')), output_field=models.FloatField())
)
).order_by('-score')
ndata = []
for d in data:
ndata.append({'user__username': d.user__username, 'score': d.score})
data = ndata
if request.user.is_authenticated:
usr = SnakeGame.objects.raw(
'''
SELECT 1 as "id",
max(
(natural_food_consumed + carrison_food_consumed + hunted_food_consumed)
/
(end_frame - start_frame)
) AS "score"
FROM "core_snakegame" LEFT OUTER JOIN "auth_user"
ON ("core_snakegame"."user_id" = "auth_user"."id")
WHERE "auth_user"."id" = %s
GROUP BY "auth_user"."id"
''', [request.user.id]
)[0]
usr = data.filter(user__username=request.user.username)[0]
else:
usr = False
return table(request, data, usr, 'Consume Rate', 'highscore')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment