diff options
| author | Brad Melin <melinbrad@gmail.com> | 2017-02-21 08:43:38 +0200 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2017-03-14 19:58:56 -0400 |
| commit | b625907a79bb1336cbc54231bdf7cace25fecaf7 (patch) | |
| tree | 824ee84d7123c31c87860e137dc48806be5b6cb8 /django | |
| parent | 3f64fd2f75342fa061338d75916c08b98f0c7797 (diff) | |
Fixed #27834 -- Added StrIndex database function.
Diffstat (limited to 'django')
| -rw-r--r-- | django/db/models/functions/__init__.py | 4 | ||||
| -rw-r--r-- | django/db/models/functions/base.py | 23 |
2 files changed, 25 insertions, 2 deletions
diff --git a/django/db/models/functions/__init__.py b/django/db/models/functions/__init__.py index eeafc1dc48..b8bb89b171 100644 --- a/django/db/models/functions/__init__.py +++ b/django/db/models/functions/__init__.py @@ -1,6 +1,6 @@ from .base import ( Cast, Coalesce, Concat, ConcatPair, Greatest, Least, Length, Lower, Now, - Substr, Upper, + StrIndex, Substr, Upper, ) from .datetime import ( Extract, ExtractDay, ExtractHour, ExtractMinute, ExtractMonth, @@ -12,7 +12,7 @@ from .datetime import ( __all__ = [ # base 'Cast', 'Coalesce', 'Concat', 'ConcatPair', 'Greatest', 'Least', 'Length', - 'Lower', 'Now', 'Substr', 'Upper', + 'Lower', 'Now', 'StrIndex', 'Substr', 'Upper', # datetime 'Extract', 'ExtractDay', 'ExtractHour', 'ExtractMinute', 'ExtractMonth', 'ExtractSecond', 'ExtractWeek', 'ExtractWeekDay', 'ExtractYear', diff --git a/django/db/models/functions/base.py b/django/db/models/functions/base.py index beac2e2d72..bb4354ac87 100644 --- a/django/db/models/functions/base.py +++ b/django/db/models/functions/base.py @@ -187,6 +187,29 @@ class Now(Func): return self.as_sql(compiler, connection, template='STATEMENT_TIMESTAMP()') +class StrIndex(Func): + """ + Return a positive integer corresponding to the 1-indexed position of the + first occurrence of a substring inside another string, or 0 if the + substring is not found. + """ + function = 'INSTR' + arity = 2 + + def __init__(self, expression, substring, **extra): + """ + expression: the name of a field, or an expression returning a string + substring: a string to find inside expression + """ + if not hasattr(substring, 'resolve_expression'): + substring = Value(substring) + expressions = [expression, substring] + super().__init__(*expressions, output_field=fields.IntegerField(), **extra) + + def as_postgresql(self, compiler, connection): + return super().as_sql(compiler, connection, function='STRPOS') + + class Substr(Func): function = 'SUBSTRING' |
