通过方法的返回结果对 Django 查询集进行排序

发布于 2024-11-27 12:39:59 字数 540 浏览 0 评论 0原文

假设我有一个比尔处理过的事情的查询集,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小姐丶请自重 2024-12-04 12:39:59

如果 thing_date() 是 python 代码中的函数,则无法让数据库对其进行排序。这意味着放置查询集没有意义。将结果输入 python 后,您必须对其进行排序。只要您不处理大量对象,这就没问题。

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

如果您有大量的 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.

qs = Things.objects.filter(user='Bill')
unsorted_results = qs.all()
sorted_results = sorted(unsorted_results, key= lambda t: t.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.

时光清浅 2024-12-04 12:39:59

请参阅这些答案以使用计算值对QuerySet进行排序:

基本上如果thing_date() 可以使用查询表达式来确定,然后您可以使用它来注释和搜索查询集。

from django.db.models import F
from django.utils import timezone
test = Things.objects.filter(user='Bill').annotate(
    thing_date=(F('<date field>') - timezone.now())  # some computation
).order_by('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.

from django.db.models import F
from django.utils import timezone
test = Things.objects.filter(user='Bill').annotate(
    thing_date=(F('<date field>') - timezone.now())  # some computation
).order_by('thing_date')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文