How to order queries by exact match first

102 views
Skip to first unread message

Alexander Todorov

unread,
Mar 6, 2013, 6:58:03 AM3/6/13
to django...@googlegroups.com
Hi guys,
I have this type of query:

.filter(name__icontains='celery')

and will possibly replace it with

.filter(Q(name='celery') | Q(name__icontains='celery'))


I want to get the results ordered by exact match first. Is this possible or I need to sort the results in my code?

Regards,
Alex
--
http://atodorov.org


Tom Evans

unread,
Mar 6, 2013, 7:09:18 AM3/6/13
to django...@googlegroups.com
On Wed, Mar 6, 2013 at 11:58 AM, Alexander Todorov
<alexx....@gmail.com> wrote:
> Hi guys,
> I have this type of query:
>
> .filter(name__icontains='celery')
>
> and will possibly replace it with
>
> .filter(Q(name='celery') | Q(name__icontains='celery'))
>
>
> I want to get the results ordered by exact match first. Is this possible or
> I need to sort the results in my code?
>

Use .extra() to additionally select out 'name = "celery"' and order by
that extra field (followed by whatever else you wanted to order by).

Eg, something like:

q = 'Broken'
TVEpisode.objects.filter(
Q(title=q) | Q(title__contains=q)
).extra(
select={'match': 'title = %s'},
select_params=(q,)
).order_by('-match', 'title')

=>

[<TVEpisode: 6x01 - Broken>, <TVEpisode: 8x15 - Broken>, <TVEpisode:
2x01 - Broken>, <TVEpisode: 2x03 - Broken>, <TVEpisode: 2x06 -
Broken>, <TVEpisode: 1x04 - A Broken Heart>, <TVEpisode: 1x01 - Angel
with a Broken Wing> .. ]

Cheers

Tom

Gabriel

unread,
Mar 6, 2013, 7:12:12 AM3/6/13
to django...@googlegroups.com

I'm not sure this is the right way, but you could drop the Q objects, use only icontains and sort by the length of 'name'

Reply all
Reply to author
Forward
0 new messages