django - 将列表转换回查询集 [英] django - convert a list back to a queryset

查看:49
本文介绍了django - 将列表转换回查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些记录,我想根据计算值对其进行排序.得到了答案在这里...像这样:

I have a handful of records that I would like to sort based on a computed value. Got the answer over here... like so:

sorted(Profile.objects.all(), key=lambda p: p.reputation)

在这样的 Profile 类上:

on a Profile class like this:

class Profile(models.Model):

    ...

    @property
    def reputation(self):
        ...

不幸的是,通用视图需要一个查询集对象,如果我给它一个列表就会抛出一个错误.

Unfortunately the generic view is expecting a queryset object and throws an error if I give it a list.

有没有办法做到这一点,返回一个查询集

或...

我可以以某种方式将列表转换为查询集吗?在 django 文档中找不到类似的内容.

Can I convert a list to a queryset somehow? Couldn't find anything like that in the django docs.

我不希望对数据进行非规范化,但我想如果必须的话我会这样做.

I am hoping not to denormalize the data, but I guess I will if I have to.

似乎获取查询集的唯一方法是您是否可以将所有逻辑都放入 sql 查询中.

it seems that the only way to get a queryset back is if you can get all of your logic into the sql queries.

如果这是不可能的,(我认为)您需要对数据进行非规范化

When that is not possible, (I think) you need to denormalize the data

推荐答案

将数据列表转换回查询毫无意义.查询对象从不保存数据;它只是代表对数据库的查询.如果您将列表设置为查询,它将不得不再次获取所有内容,这将是多余的,而且性能非常差.

There is no point in converting a data list back to a query. A query object never holds data; it just represents a query to the database. It would have to fetch everything again if you made your list to a query, and that would be redundant and very bad performance-wise.

你可以做什么:

  • 描述如何计算 reputation 字段;有可能以某种方式对数据库中的数据进行排序.
  • 将视图修改为不需要查询对象.如果它需要进行额外的过滤等,这应该在任何排序之前完成,因为排序将花费更少的时间和更少的条目(并且将从数据库中获取更少的数据.)所以你可以将过滤后的查询对象发送到排序在您将其发送到模板之前的函数(它不应该关心它是查询还是列表.)
  • Describe how the reputation field is calculated; it's probably possible to order the data in the database somehow.
  • Modify the view to not require a query object. If it needs to do additional filtering etc. this should be done before any ordering, since the ordering will take less time with less entries (and less data will be fetched from the database.) So you could send the filtered query object to the sort function just before you send it to the template (which shouldn't care whether it's a query or a list.)

这篇关于django - 将列表转换回查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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