title: How to make/use a custom database function in Django
body: <p><strong>Prologue:</strong></p>
  
  <p>This is a question arising often in SO:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/45631855/equivalent-of-postgis-st-makevalid-in-django-geos/">Equivalent of PostGIS ST_MakeValid in Django GEOS</a></li>
  <li><a href="https://stackoverflow.com/questions/19144834/geodjango-how-to-buffer-from-point/45879956#45879956">Geodjango: How to Buffer From Point</a></li>
  <li><a href="https://stackoverflow.com/questions/46455081/get-random-point-from-django-polygonfield/46464362#46464362">Get random point from django PolygonField</a></li>
  <li><a href="https://stackoverflow.com/questions/46427115/django-custom-for-complex-func-sql-function/46490971#46490971">Django custom for complex Func (sql function)</a></li>
  </ul>
  
  <p>and can be applied to the above as well as in the following:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/43890131/django-f-expression-on-datetime-objects/43890979#43890979">Django F expression on datetime objects</a></li>
  </ul>
  
  <p>I wanted to compose an example on SO Documentation but since it got shut down on August 8, 2017, I will follow the suggestion of <a href="https://meta.stackoverflow.com/questions/354217/sunsetting-documentation/354302#354302">this widely upvoted and discussed meta answer</a> and write my example as a self-answered post.</p>
  
  <p>Of course, I would be more than happy to see any different approach as well!!</p>
  
  <hr>
  
  <p><strong>Question:</strong></p>
  
  <p>Django/GeoDjango has some database functions like <a href="https://docs.djangoproject.com/en/1.11/ref/models/database-functions/#lower" rel="noreferrer"><code>Lower()</code></a> or <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/gis/functions/#makevalid" rel="noreferrer"><code>MakeValid()</code></a> which can be used like this:</p>
  
  <pre><code>Author.objects.create(name='Margaret Smith')
  author = Author.objects.annotate(name_lower=Lower('name')).get()
  print(author.name_lower)
  </code></pre>
  
  <p>Is there any way to use and/or create my own custom database function based on existing database functions like:</p>
  
  <ul>
  <li><a href="https://www.w3schools.com/sql/func_mysql_position.asp" rel="noreferrer"><code>Position()</code></a> (MySQL)</li>
  <li><a href="http://www.sqlitetutorial.net/sqlite-functions/sqlite-trim/" rel="noreferrer"><code>TRIM()</code></a> (SQLite)</li>
  <li><a href="https://postgis.net/docs/ST_MakePoint.html" rel="noreferrer"><code>ST_MakePoint()</code></a> (PostgreSQL with PostGIS)</li>
  </ul>
  
  <p>How can I apply/use those functions in Django/GeoDjango ORM?</p>