2

I need too annotate the result of a regex lookup in a When() conditional expression using the then parameter, DB is Postgresql.

For example you can use the SubStr() function to get a substring of a field, I want to be able to use a regular expression instead of a positional substring.

I was thinking some custom function using 'REGEXP_MATCHES', I'm not sure how I'd do this though, or if it's even necessary.

qs = SomeModel.objects.all()

pattern = r'regex'

qs = qs.annotate(
    match=Case(
        When(
            some_model_field__regex=pattern,
            then=Regex('some_model_field', pattern)
        ),
        output_field=CharField()
    )
)

I want the annotation to be the result of the pattern match.

  • "the result of the pattern match" would be true or false (boolean, whether the regex matches or not). But the output_field is a CharField, so what you probably mean is that you want to return a match group or the string that actually matched (group 0)? – Risadinha Jan 25 '19 at 18:09
  • 1
    Yes, apologies for not making that clearer, I'm looking for the match group, not the boolean. So if say the pattern was r'\/([0-9]{4})' I'd want the annotation to be the matching number. – Craig Minchin Jan 25 '19 at 18:17

0 Answers0