Код: Выделить всё
from django.db.models import Func
class Position(Func):
function = 'POSITION'
template = "%(function)s(LOWER('%(substring)s') in LOWER(%(expressions)s))"
template_sqlite = "instr(lower(%(expressions)s), lower('%(substring)s'))"
def __init__(self, expression, substring):
super(Position, self).__init__(expression, substring=substring)
def as_sqlite(self, compiler, connection):
return self.as_sql(compiler, connection, template=self.template_sqlite)
Код: Выделить всё
class A(models.Model):
title = models.CharField(max_length=30)
data = ['Port 2', 'port 1', 'A port', 'Bport', 'Endport']
for title in data:
A.objects.create(title=title)
search = 'port'
qs = A.objects.filter(
title__icontains=search
).annotate(
pos=Position('title', search)
).order_by('pos').values_list('title', flat=True)
# result is
# ['Port 2', 'port 1', 'Bport', 'A port', 'Endport']
"Он легко выходит из строя by ') in '') from myapp_suburb; drop ...
ожидалось, что имя приложения — «myapp и автофиксация включена».
Основная проблема в том, что лишние данные (
Код: Выделить всё
substringЯ не могу найти способ защиты от этого в Django.
Я создал репозиторий (djposfunc), где вы можете протестировать любое решение.
Подробнее здесь: https://stackoverflow.com/questions/464 ... l-function
Мобильная версия