Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impossible to order by time in django

I 've got a real problem that i can't fix. I'm trying to order a transaction by time but everything I do for ordering the queryset.... nothing work.

here is my model

class Transaction(models.Model):
   collocDonneur=models.ForeignKey(Person,related_name="collocDonneur",on_delete=models.SET_NULL,null=True, blank=True)
    collocReceveur=models.ForeignKey(Person,related_name="collocReceveur",on_delete=models.SET_NULL,null=True, blank=True)
    point=models.IntegerField(null=False)
    raison=models.TextField(null=True,blank=True)
    date=models.DateTimeField(default=timezone.now)



    class Meta:
        verbose_name="Transaction"

and here is my view :

def vote(request):
    person=Person.objects.all()
    transactions=Transaction.objects.all()
    transactions.order_by('date')
    return render(request,"liste.html",locals())

even if I replace 'date' by '-date', nothing work, even if i do a reverse() on the queryset...

like image 963
Lucas Bouvarel Avatar asked Jan 23 '26 07:01

Lucas Bouvarel


1 Answers

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.
like image 64
Willem Van Onsem Avatar answered Jan 24 '26 21:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!