简体   繁体   中英

SQLAlchemy: Execute/Add a function to a column in sqlalchemy

I'm using SQLAlchemy and I have a query from which one of the columns I obtain is a constant QUOTE_STATUS_ERROR, the values in this column are integers. Since the constant value doesn't mean anything to the end-user, I'd like to convert that value from within the query itself to show a string by mapping the values of that column to a dictionary that I have in the app using a function I have in place for that purpose already. I haven't been able to find a way to implement it since Columns in the query are object not value of the column itself. To make my question clear this is an example of what I have:

Query:

q = meta.session.query(MyModel.id, MyModel.quote_status).join(AnotherModel).subquery("q")

Function I want to use:

def get_status_names(status_value):
    return QUOTE_STATUS_NAMES[status_value]

Is there a way to this directly from SQLAlchemy by attaching/passing a function (get_status_names()) to the column (MyModel.quote_status). If not what could be the best approach? I prefer not iterate over the values once I get the results in case the list of results is extensive. I would appreciate a push in the right direction.

UPDATE: I'm joining the resulting subquery with other tables

There are a few things you can do.

Off the top of my head...

  1. If you just want to display things, you can use a property decorator:

QUOTE_STATUS__ID_2_NAME = {}

class MyModel(object):
    id = Column()
    quote_status_id = Column()

    @property
    def quote_status_string(self):
        if self.quote_status_id:  
            return QUOTE_STATUS__ID_2_NAME[self.quote_status_id] 
        return None

  1. If you want to render/accept strings and have sqlalchemy convert from string/int transparently, you can use a TypeDecorator -- http://docs.sqlalchemy.org/en/rel_0_9/core/types.html#custom-types

Personally, I usually go for the property decorator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM