如何按外部值对Django QuerySet进行排序? [英] How do I sort a Django QuerySet by an external value?
问题描述
我有一个由(id,rank)对组成的字典.我想对ID执行Django查询,以使所得的查询集按等级(降序)排序.
I have a dict made up of (id, rank) pairs. I'd like to perform a Django query on the ids such that the resultant queryset is ordered by rank (descending).
获取查询集很容易:
rankings = {...}
result = MyModel.objects.filter(id__in=rankings.keys())
答案似乎应该包含某种注释,我可以将其用作order_by的一部分,但我不知道该如何到达.
It seems like the answer should involve some sort of annotation that I can use as part of the order_by but I can't figure out how to get there.
我忽略了提及我需要将结果作为QuerySet的原因,因为这是asteapie API管道的一部分.
I neglected to mention that I need the result to be a QuerySet as this is part of a tastypie API pipeline.
推荐答案
我能解决的唯一方法是创建一个与主要模型相关的新排名模型.在每个查询中,我将排名项目插入该模型,然后能够通过该关系执行order_by.(使用注释将等级添加到学校记录中.)
The only way I could figure out to solve this is to create a new ranking model related to primary model. On each query I insert the ranking items into that model and then am able to execute the order_by via the relation. (Using annotate to add the rank to the school records.)
class UserSchoolRanking(models.Model):
user = models.ForeignKey(User)
school = models.ForeignKey(School)
rank = models.IntegerField()
bulk_user_school_rank = [UserSchoolRank(user=user, school_id=k, rank=v)
for k, v in rankings.iteritems()]
UserSchoolRank.objects.bulk_create(bulk_user_school_rank)
schools = School.objects.filter(userschoolrank__user=user)\
.annotate(rank=Min('userschoolrank__rank'))\
.order_by('-userschoolrank__rank')
这篇关于如何按外部值对Django QuerySet进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!