Django-将列表转换回查询集

我有一些记录要根据计算值进行排序。得到答案 这边... 就像这样:

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

像这样的 Profile 类:

class Profile(models.Model):


...


@property
def reputation(self):
...

遗憾的是,通用视图期望查询集对象,如果我给它一个列表,它就会抛出一个错误。

有没有一种方法可以返回一个查询集

或者..。

我能以某种方式将一个列表转换为一个查询集吗? 在 django 文档中找不到任何类似的东西。

我希望不要使数据非规范化,但如果必须这样做的话,我想我会的。

更新/回答:

似乎获得查询集的唯一方法是将所有逻辑都放入 sql 查询中。

当这不可能时,(我认为)您需要将数据反规范化

80848 次浏览

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.

What you can do:

  • 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.)

Ok...this post is now old BUT what you could do is get all the ids of the objects in your list, then perform a model.objects.filter(pk__in=list_of_ids)