My tool in Django can add users and games and then see them in a table. I want to add the rank, but have no idea how to do it.
class BeerPongRankingTable(models.Model):
rank = models.IntegerField(default=0, null=False)
username = models.CharField(max_length=30, default='',
null=False)
wins = models.IntegerField(default=0, null=False)
games = models.IntegerField(default=0, null=False)
created_at = models.DateField(default=date.today)
CodePudding user response:
I made views Rank, in which the wins field is sorted in reverse order. Then loop from 1 to the number of rows in the database. At each iteration, i is assigned to aaa[i - 1].rank. The updated data is passed to the dictionary and displayed on the page via the rank_templ.html template. Replace the 'samplesite' prefix in the 'samplesite/rank_templ.html' line with your application name.
That is, in my case, when I go to the address: http://localhost:8000/samplesite/rank/
sorting occurs, the database is updated, followed by the display of the page.
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path("rank/", Rank),
]
views.py
from .models import BeerPongRankingTable
def Rank(request):
aaa = BeerPongRankingTable.objects.order_by('-wins')
for i in range(1, len(aaa) 1):
aaa[i - 1].rank = i
aaa[i - 1].save()
print('aaa[i].wins', aaa[i-1].wins, type(aaa))
context = {'fff': aaa}
return render(request, 'samplesite/rank_templ.html', context)
rank_templ.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
{% for aa in fff %}
<p>{{aa.rank}}</p>
<p>{{aa.username}}</p>
{% endfor %}
</body>
</html>