我遇到了无法解决的实际问题。我正在尝试按时间对交易进行排序,但我为排序查询集所做的一切......都没有用。
这是我的模型
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"
这是我的观点:
def vote(request):
person=Person.objects.all()
transactions=Transaction.objects.all()
transactions.order_by('date')
return render(request,"liste.html",locals())
即使我将“日期”替换为“-date”,也没有任何效果,即使我在查询集上执行了 reverse()...
最佳答案
如果您调用 .order_by(..)
你不对给定的查询集进行排序,你构建了一个新的查询集,它是旧查询集的副本,但项目是有序的。您可以将这些以与字符串类似的方式来考虑:您不能更改字符串,您只能制作字符串的(修改后的)副本。严格来说,您可以更改 QuerySet
的状态,但这通常不是一个好主意,通过更改 QuerySet
持有的值(以及底层的 .query
),您很可能会打破一些假设,从而构造一个无效的查询,或者破坏缓存机制。
因此,您应该构造一个查询集,如下所示:
def vote(request):
persons = Person.objects.all()
transactions = Transaction.objects.<b>order_by('date')</b>
return render(
request,
'liste.html',
{'persons': persons, 'transactions': transaction}
)
Extra notes:
- since
person
is a collection ofPerson
s, it is better to name itperson<b>s</b>
, not.person
- 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.
关于python - 不可能在 Django 中按时间排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58157045/