我想在 django 中创建一个搜索,它的顺序是 istartswith,而不是 icontains

i want to create a search in django which have order by istartswith first than icontains

def autocomplete(request):
    template_name='searchresults.html'
    if 'term' in request.GET:
        qs=Post.objects.filter(Q(title__istartswith=request.GET.get('term'))|Q(content__icontains=request.GET.get('term')))
        titles=list()
        for post in qs:
            titles.append(post.title)
        return JsonResponse(titles, safe=False)
    return render(request, template_name)

我怎样才能以这样的方式对它们进行排序,如果它以术语开头,则将其排序为第一个,将包含它但不以它开头的排序为第二个

你可以利用.union(…) [Django-doc]:

term = request.GET.get('term')

qs = Post.objects.filter(
    title__istartswith=term
)<b>.union(</b>Post.objects.filter(
    content__icontains=term
)<b>)</b>

.annotate(…) [Django-doc]:

from django.db.models import BooleanField, ExpressionWrapper, Q

term = request.GET.get('term')

qs = Post.objects.filter(
    Q(title__istartswith=term) | Q(content__icontains=term)
).annotate(
    <b>is_start=</b>ExpressionWrapper(
        Q(title__istartswith=term),
        output_field=BooleanField()
    )
).order_by(<b>'-is_start'</b>)