Simple query ranking in django template

I have a model in a simple django application that records the score for people entering a competition. I have two model objects: Entry and Person. Each record has an identity, and a person has several records.

I want to create a page that shows each user, their total score and their rank.

The command I have received so far is as follows:

Entry.objects.values('person__name').annotate(total=Sum('score')).order_by('-total')

I can get the result of this on the page using the for block. The only thing I do not understand is the rank.

What would be the best way to add a numerical record rank to each record, including the fact that when two points coincide, the rank reflects this (ie "4 =")? Would it be better to try to do this in the template using forblock.counter and some lookahead / behind mechanism, or try to process this field in the request itself?

+3
source share
3 answers

These kinds of things are very complicated. I would actually do all the work in the view, changing the set of queries there and passing it to the template.

rank = 1
previous = None
entries = list(entries)
previous = entries[0]
previous.rank = 1
for i, entry in enumerate(entries[1:]):
    if entry.value != previous.value:
        rank = i + 2
        entry.rank = str(rank)
    else:
        entry.rank = "%s=" % rank
        previous.rank = entry.rank
    previous = entry
+6
source

Keep it simple, use the loop.counter or loop.revcounter template, do not confuse with the request in this case, I think.

+1
source

, person.name, . total .

Entry.objects.values('person__name', 'total').annotate(total=Sum('score')).order_by('-total')

EDIT:

:

Person.objects.values('name').annotate(total=Sum('entries__score')).order_by('-total')
-1

Source: https://habr.com/ru/post/1788537/


All Articles