On Wed, Mar 6, 2013 at 11:58 AM, Alexander Todorov
<[email protected]> 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

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to