[Django]-Impossible to order by time in django

5👍

If you call .order_by(..) you do not sort the given queryset, you construct a new one that is a copy of the old one, but where the items are ordered. You could think of these in a similar way as strings: you can not alter a string, you can only make a (modified) copy of the string. Strictly speaking, you can alter the state of a QuerySet, but that is usually not a good idea, by changing values hold by the QuerySet (and the underlying .query), it is likely that you will break some assumption, and thus construct an invalid query, or defeat the caching mechanism.

You thus should construct a queryset like:

def vote(request):
    persons = Person.objects.all()
    transactions = Transaction.objects.order_by('date')
    return render(
        request,
        'liste.html',
        {'persons': persons, 'transactions': transaction}
    )

Extra notes:

  1. since person is a collection of Persons, it is better to name it persons, not person.
  2. please do not use locals() this is an anti-pattern, since you make it unclear what you pass to the context. If you later aim to optimize the view for example, you might remove some variable by mistake. You furthermore easily start passing too much variables than the ones you really need.

Leave a comment