title: Django custom for complex Func (sql function)
body: <p>In the process of finding a solution for <a href="https://stackoverflow.com/questions/46398198/django-orm-orderby-exact-prominent-match-to-be-on-top/46400073?noredirect=1#comment79807900_46400073">Django ORM order by exact</a>, I created a custom django Func:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>which works as follows:</p>
  
  <pre><code>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'] 
  </code></pre>
  
  <p>But as @hynekcer commented: </p>
  
  <blockquote>
    <p>"It <strong>crashes easily</strong> by <code>') in '') from myapp_suburb; drop ...</code>
    expected that the name of the app is "myapp and autocommit is enabled."</p>
  </blockquote>
  
  <p>The main problem is that extra data (<code>substring</code>) got into the template without sqlescape which leaves the app vulnerable to SQL injection attacks.</p>
  
  <p>I cannot find which is the Django way to protect from that. </p>
  
  <hr>
  
  <p>I created a <a href="https://github.com/gitavk/djposfunc" rel="noreferrer">repo (djposfunc)</a> where you can test any solution.</p>