简体   繁体   English

如何按字典中的值对模型排序?

[英]How to sort model by values in a dictionary?

In Django, I have a model, and I will have a dictionary having the id's of objects in this model as keys, and a weight as values. 在Django中,我有一个模型,我将有一个字典,其中以该模型中对象的id为键,以权重为值。 I would like to use these weights in an order_by: 我想在order_by中使用这些权重:

MyModel.objects.filter(title__icontains=query).order_by( 'value_from_the_dictionary' )

How to make this work? 如何使这项工作?

I can't put the weights in the model, as they will be different in each call of this view, and I don't want to save them anywhere, they will be calculated on each query of the URL. 我无法将权重放入模型中,因为权重在此视图的每次调用中都会有所不同,并且我不想将其保存在任何位置,它们将根据URL的每次查询进行计算。

Sorting in order_by is done by the database, so if those elements aren't in the database you can't order by them. order_by排序是由数据库完成的,因此,如果这些元素不在数据库中,则无法对其进行排序。 You will have to get the queryset and then do the ordering in Python. 您将必须获取queryset,然后在Python中进行排序。

qs = MyModel.objects.filter(title__icontains=query)
qs.sort(key=lambda x: mydict[x])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM