我将我工作的Django-App复制到一个新项目中,现在我遇到了一个无法解决的问题。
我会检查新游戏时间是否低于旧游戏时间。
if playtime < HighscoreEasy.objects.filter(player=player).order_by('score').first().score:
我期待这样的事情:
>>> HighscoreEasy.objects.filter(player=2).order_by('score').first().score
8.9754946231842
>>> playtime = 10.0
>>> playtime < HighscoreEasy.objects.filter(player=2).order_by('score').first().score
False
Environment:
Request Method: POST
Request URL: https://www.maik-kusmat.de/kopfrechnen/results/
Django Version: 1.11.5
Python Version: 3.5.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'home',
'contact',
'kopfrechnen',
'braces']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware']
Traceback:
File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/home/pi/Dev/mkenergy/src/kopfrechnen/views.py" in kopfrechnen_results
168. if playtime < HighscoreEasy.objects.filter(player=player).order_by('score').first().score:
Exception Type: TypeError at /kopfrechnen/results/
Exception Value: unorderable types: float() < HighscoreEasy()
以下是我的代码中带有问题的代码段:
def kopfrechnen_results(request):
end_time = time.time()
if 'start_time' in request.session:
start_time = request.session['start_time']
else:
template = loader.get_template('kopfrechnen/kopfrechnen.html')
context = {'error': 'Starte ein neues Spiel immer von hier.'}
return HttpResponse(template.render(context, request))
if 'tasks' in request.session:
tasks = request.session['tasks']
else:
template = loader.get_template('kopfrechnen/kopfrechnen.html')
context = {'error': 'Starte ein neues Spiel immer von hier.'}
return HttpResponse(template.render(context, request))
if 'difficulty' in request.session:
difficulty = request.session['difficulty']
else:
template = loader.get_template('kopfrechnen/kopfrechnen.html')
context = {'error': 'Starten Sie ein neues Spiel von hier.'}
return HttpResponse(template.render(context, request))
del request.session['start_time']
del request.session['tasks']
del request.session['difficulty']
message1 = ""
message2 = ""
player = request.user
playtime = end_time - start_time
template = loader.get_template('kopfrechnen/kopfrechnen_results.html')
answers = []
inputs = []
right_answers = 0
for i in range(5):
if request.POST.get('task' + str(i)):
inputs += [int(request.POST.get('task' + str(i)))]
else:
inputs += [999999]
answers += [int(tasks[i].get('c'))]
if inputs[i] == answers[i]:
right_answers += 1
success = False
if right_answers == 5:
success = True
if difficulty == 'easy':
try:
if HighscoreEasy.objects.order_by('score').first() is not None:
if playtime < HighscoreEasy.objects.values_list('score', flat=True)[0]:
message1 = "Neue absolute Bestzeit!"
elif HighscoreEasy.objects.filter(player=player).order_by('score').first() is not None:
if playtime < HighscoreEasy.objects.filter(player=player).order_by('score').first().score:
message1 = "Neue persönliche Bestzeit!"
else:
message1 = ""
else:
message1 = "Neue absolute Bestzeit!"
place = HighscoreEasy.objects.filter(score__lt=playtime).values_list('score', flat=True).count() + 1
if place > 10:
message2 = "Super, aber leider keine neue Bestzeit in der Top 10."
elif place <= 10:
message2 = "Super, du bist auf Platz " + str(place) + " gelandet."
try:
if HighscoreEasy.objects.get(player=player):
entry = HighscoreEasy.objects.get(player=player)
if playtime < entry.score:
entry.score = playtime
entry.created = timezone.now()
entry.save()
if playtime > entry.score:
message2 = " Du konntest dich leider nicht verbessern."
except:
entry = HighscoreEasy(score=playtime, player=player)
entry.save()
except IndexError:
message1 = "Fehler! Bitte melde diesen Fehler"
我的模特:
class HighscoreEasy(models.Model):
player = models.ForeignKey(settings.AUTH_USER_MODEL, default=settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
verbose_name="player_easy")
created = models.DateTimeField(default=timezone.now)
score = models.FloatField()
class Meta:
ordering = ["score"]
答案 0 :(得分:0)
我解决了这个问题。
我为Usermodel
定义了 str 属性def __str__(self):
return self.user.username
但在我的数据库中,我将通过id获取用户。愚蠢,但发生了