通过方法的返回结果对Django查询集进行排序 [英] Ordering a Django queryset by the returned results of a method

查看:114
本文介绍了通过方法的返回结果对Django查询集进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我对Bill所做的事情有一个查询集:

Let's say I have a queryset of things Bill has worked on like this:

test=Things.objects.filter(user='Bill')

现在我想按分配给它们的日期对所有这些东西进行排序法案。不幸的是,分配日期不是事物模型中的字段。相反,有一种名为 thing_date()的方法可以解决该问题并返回日期。例如,以下内容:

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?

毫无疑问,其他人以前也走过这条路。 链接

Not surprisingly other folks have been down this road before. Link

推荐答案

如果 thing_date()是python代码中的一个函数,您无法获取对其进行排序的数据库。这意味着放置查询集没有任何意义。将结果放入python后,您必须对结果进行排序。只要您不处理大量对象,就可以了。

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.

qs = Things.objects.filter(user='Bill')
unsorted_results = qs.all()
sorted_results = sorted(unsorted_results, key= lambda t: t.thing_date())

如果您有很多物品,那么您必须计算将 thing_date 放入数据库的某种方式,否则您将遇到内存问题。

If you've got a very large number of Things then you'll have to figure some way to get thing_date into the database or else you'll have memory issues.

这篇关于通过方法的返回结果对Django查询集进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆