from django.db.model import Q, ExpressionWrapper, BooleanField
....
# Your original setup.
search_term = 'Game of'
data = MyModel.objects.filter(name__icontains=search_term)
# Encapsulate the comparison expression.
expression = Q(name__startswith=search_term)
# Wrap the expression to specify the field type.
is_match = ExpressionWrapper(expression, output_field=BooleanField())
# Annotate each object with the comparison.
data = data.annotate(my_field=is_match)
# Order by the annotated field in reverse, so `True` is first (0 < 1).
data = data.order_by('-my_field')
....
Django在提出这个问题后添加了新的特性,现在以本机方式处理这个用例。在
您可以使用Django的QuerySet API中的以下功能通过任意比较来排序结果:
output_field
控制ModelField
类型。在本例中,类型是布尔型。在True
/False
字段进行排序。在True
值。在你描述的排序是主观的,数据库中没有类似的数据(我知道)。如果像这样的特性很重要,那么您可能需要研究一下Solr或{a2}这样的搜索引擎,您可以在其中配置如何确定相关性得分。在
相关问题 更多 >
编程相关推荐