python - 不可能在 Django 中按时间排序

标签 python django django-queryset

我遇到了无法解决的实际问题。我正在尝试按时间对交易进行排序,但我为排序查询集所做的一切......都没有用。

这是我的模型

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:

  1. since person is a collection of Persons, it is better to name it person<b>s</b>, 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.

关于python - 不可能在 Django 中按时间排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58157045/

相关文章:

python - 是否可以强制 float 的指数或尾数匹配另一个 float (Python)?

python - Django 过滤对象 F ('duration' ) 从现在开始

json - 使用 django query set values() 索引到 JSONField

python - 使用 Python 3.4.1 导入 http.client encouter 导入错误

python - Numpy argwhere 不等式条件

django - 如何从 Django 表单中删除必需的属性

python - 使用缓存装饰器在 Python 中运行单元测试

python - 如何根据 ReferenceProperty 的属性查询记录? (应用引擎上的 Django)

django - 我可以对查询集返回对象进行排序以便对结果进行排序吗

python - RabbitMQ中如何实现同步生产者调用