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