通过方法的返回结果对 Django 查询集进行排序
假设我有一个比尔处理过的事情的查询集,如下所示:
test=Things.objects.filter(user='Bill')
现在我想按分配给比尔的日期对所有这些事情进行排序。不幸的是,分配日期不是事物模型中的字段。相反,有一个名为 thing_date() 的方法可以计算并返回日期。例如,以下内容:
Thingobject.thing_date()
...返回日期。我想我想做的是这样的:
test=Things.objects.filter(user='Bill').order_by(self__thing_date())
......但我知道这是行不通的。还有别的办法吗?
更新
毫不奇怪,其他人以前也曾走过这条路。 链接
Let's say I have a queryset of things Bill has worked on like this:
test=Things.objects.filter(user='Bill')
Now I want to sort all those things by the date they were assigned to bill. Unfortunately the assignment date isn't a field in the Thing model. Instead there's a method named thing_date() that figures it out and returns the date. For example, the following:
Thingobject.thing_date()
...returns the date. I guess what I want to do is something like:
test=Things.objects.filter(user='Bill').order_by(self__thing_date())
...but I know that won't work. Is there another way?
Update
Not surprisingly other folks have been down this road before. Link
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
thing_date()
是 python 代码中的函数,则无法让数据库对其进行排序。这意味着放置查询集没有意义。将结果输入 python 后,您必须对其进行排序。只要您不处理大量对象,这就没问题。如果您有大量的
Things
,那么您必须想办法将thing_date
存入数据库,否则您将遇到内存问题。If
thing_date()
is a function in python code, you can't get the database to sort on it. Which means it doesn't make sense to put the queryset. You'll have to sort the results after you get them into python. This will be fine so long as you're not dealing with a very large number of objects.If you've got a very large number of
Things
then you'll have to figure some way to getthing_date
into the database or else you'll have memory issues.请参阅这些答案以使用计算值对
QuerySet
进行排序:基本上如果
thing_date()
可以使用查询表达式来确定,然后您可以使用它来注释和搜索查询集。see these answers to use a computed value to sort a
QuerySet
:Basically if
thing_date()
can be determined using a query expression, then you can use it to annotate and search the query set.