Skip to content Skip to sidebar Skip to footer

Django Orm Orderby Exact / Prominent Match To Be On Top

I need to order the results based on the length of match in Django ORM. I have a Suburb table with location details in name field. I have a requirement to search the table with gi

Solution 1:

Django 2.0 implements a function

StrIndex(string, substring)

Returns a positive integer corresponding to the 1-indexed position of the first occurrence of substring inside string, or 0 if substring is not found.

Example:

from django.db.models.functions import StrIndex

qs = (
    Suburb.objects
    .filter(name__contains='America')
    .annotate(search_index=StrIndex('name', Value('America')))
)

Solution 2:

based on func

solution for postgres (and should work in mysql, but not testing):

from django.db.models import Func

class Position(Func):
    function = 'POSITION'
    arg_joiner = ' IN '

    def __init__(self, expression, substring):
        super(Position, self).__init__(substring, expression)


Suburb.objects.filter(
    name__icontains=search).annotate(
    pos=Position('name', search)).order_by('pos')

EDIT: according to Tim Graham's fix, recommended in Django docs - Avoiding SQL injection.

Post a Comment for "Django Orm Orderby Exact / Prominent Match To Be On Top"