Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: how to perform regexp_replace on column values

I am trying to do the equivalent of cast(regexp_replace(entry.page_title,'.*::: ','') AS INT) using SQLAlchemy.

I've seen that you can use hybrid properties to perform functions on ORM-mapped classes. I've tried the following but I can't really see how you can use the hybrid properties to do string replace.

class Entry(object):

    def __init__(self, page_title):
        self.page_title = page_title

    @hybrid_property
    def original_brand_id(self):
        return self.page_title.partition(' ::: ')[-1]
        ###OR ALSO TRIED DOING:
        return re.sub(r'[.*::: ]','',self.page_title)

I know that the issue is that I'm wanting to treat Entry's page_title as a string when it's actually an InstrumentedAttribute. But I'm not clear on how to get the string value, to get this to do what I want.

Is it even possible?

like image 800
hello-klol Avatar asked Mar 19 '14 15:03

hello-klol


1 Answers

Turns out there exists a func for this so I can do

@hybrid_property
def original_brand_id(self):
    return cast(func.regexp_replace(self.page_title, '.*::: ',''), Numeric)

I would just delete this question but it took me such a long time of Google searching to find that out I'm just going to leave this here in case anyone else needs it.

like image 61
hello-klol Avatar answered Nov 01 '22 21:11

hello-klol