From b625907a79bb1336cbc54231bdf7cace25fecaf7 Mon Sep 17 00:00:00 2001 From: Brad Melin Date: Tue, 21 Feb 2017 08:43:38 +0200 Subject: Fixed #27834 -- Added StrIndex database function. --- django/db/models/functions/__init__.py | 4 ++-- django/db/models/functions/base.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) (limited to 'django') 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' -- cgit v1.3