Skip to content

Instantly share code, notes, and snippets.

@jarshwah
Created April 4, 2016 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarshwah/769a0ea10c280de34bd59f92a051dfae to your computer and use it in GitHub Desktop.
Save jarshwah/769a0ea10c280de34bd59f92a051dfae to your computer and use it in GitHub Desktop.
Use inner expressions
class ConcatWords(Func):
arg_joiner = " || ' ' || "
template = '%(expressions)s'
class SearchVector(SearchVectorCombinable, Func):
function = 'to_tsvector'
_output_field = SearchVectorField()
def __init__(self, *expressions, **extra):
expressions = [ConcatWords(*[Coalesce(expression, Value('')) for expression in expressions])]
config = extra.get('config')
if hasattr(config, 'resolve_expression'):
expressions.insert(0, config)
elif config is not None:
expressions.insert(0, Value(config))
super(SearchVector, self).__init__(*expressions, **extra)
weight = self.extra.get('weight')
if weight is not None and not hasattr(weight, 'resolve_expression'):
weight = Value(weight)
self.weight = weight
def as_sql(self, compiler, connection, function=None, template=None):
if template is None:
template = self.template
sql, params = super(SearchVector, self).as_sql(compiler, connection, function=function, template=template)
print(sql, params)
extra_params = []
if self.weight:
weight_sql, extra_params = compiler.compile(self.weight)
sql = 'setweight({}, {})'.format(sql, weight_sql)
return sql, params + extra_params
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment