1
0
mirror of https://github.com/django/django.git synced 2025-10-24 06:06:09 +00:00

Fixed #27834 -- Added StrIndex database function.

This commit is contained in:
Brad Melin
2017-02-21 08:43:38 +02:00
committed by Tim Graham
parent 3f64fd2f75
commit b625907a79
5 changed files with 124 additions and 3 deletions

View File

@@ -237,6 +237,38 @@ Usage example::
``Now()`` uses ``STATEMENT_TIMESTAMP`` instead. If you need the transaction
timestamp, use :class:`django.contrib.postgres.functions.TransactionNow`.
``StrIndex``
============
.. class:: StrIndex(expression, substring, **extra)
.. versionadded:: 2.0
Returns a positive integer corresponding to the 1-indexed position of the
first occurrence of ``substring`` inside another string, or 0 if the substring
is not found.
Usage example::
>>> from django.db.models.functions import StrIndex
>>> Author.objects.create(name='Margaret Smith')
>>> Author.objects.create(name='Smith, Margaret')
>>> Author.objects.create(name='Margaret Jackson')
>>> authors = Author.objects.annotate(
... smith_index=StrIndex('name', 'Smith')).order_by('smith_index')
>>> authors.first().smith_index
0
>>> authors = Author.objects.annotate(
... smith_index=StrIndex('name', 'Smith')).filter(smith_index__gt=0)
<QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>
.. warning::
In MySQL, a database table's :ref:`collation<mysql-collation>` determines
whether string comparisons (such as the ``expression`` and ``substring`` of
this function) are case-sensitive. Comparisons are case-insensitive by
default.
``Substr``
==========