开发者

Yet another QuerySet custom ordering problem

Lots of searchi开发者_运维知识库ng, found nothing so far.

In my django app, Model_X is rated by my users using a very standard ratings model. I have a standalone function that processes a LOT of data and when given a user instance, returns a list of tuples. The first value corresponds to the primary key for an instance of Model_X, and the second is the predicted rating. For example, it might return the following list of tuples.

[(1L, 5.25), (5L, 3.1), (23L, 1.83)]

I need to return a QuerySet (and it needs to be a QuerySet) of Model_X, containing only the instances listed in the tuples, sorted by these predicted ratings from the tuples.


If your list of rating tuples is already ordered you might be able to use something from Ordering by the order of values in a SQL IN() clause.

If you're using MySQL then the field() function should work for you. Pull all the ids from your sorted rating tuples, [x[0] for x in sorted_tuples] and then use that list of ids to build your where clause, e.g. (untested),

Model_X.objects.raw('select * from myapp_model_x where id in (5,1,23) order by field(id,5,1,23)']) 


Use a list instead of a QuerySet. You can easily build it using in_bulk

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜