Calling sqlalchemy.func on column

68 views
Skip to first unread message

Balaji Pattewar

unread,
Feb 11, 2016, 9:39:13 PM2/11/16
to sqlalchemy
Hi all,

I have Sqlite table from which I can execute HEX to convert value to HEX. 


CREATE TABLE hosts(
        name TEXT,
        mac INTEGER,
        ipv4 INTEGER,
}


 Running query  "select HEX(mac)  from  hosts" give me address in HEX format.


Now I am using Sqlalchemy.orm to read the rows from of hosts table  in the form of  Orm instance.

 class Host(Base):
    __tablename__ = 'hosts'
    __table_args__ = {'autoload': True}

How should I define Column so that I get mac address as HEX rather than integer. I mean when 
Sqlalchemy query database using session.query(Host).all()

it should run underline query as "select name, HEX(mac), ipv4 from hosts"
not  "select name, mac, ipv4 from hosts"

Thanks in advance,

Regards
Balaji



 

Mike Bayer

unread,
Feb 11, 2016, 10:49:33 PM2/11/16
to sqlal...@googlegroups.com
the most classical way to do this is via column_property():

class Host(Base):
__tablename__ = 'hosts'
id = Column(Integer, primary_key=True)
_mac = Column('mac', Integer)
mac = column_property(func.hex(_mac))

the autoload here makes things a little more strange, we're defining
"mac" as a Column even though it is reflected just so that we have
something to refer to.

If you don't define it, then you need to add the property after the
Host class exists, so that the Table is there and has been autoloaded
and you'll be able to get to Host.mac.

It might also be possible to use autoload, not define "mac" as a column
up front, and use @declared attr (see
http://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/declarative/mixins.html#mixing-in-deferred-column-property-and-other-mapperproperty-classes)
in order to refer to the column after the autoload, but I'm not sure if
the order of operations works out for that to work.




>
> Thanks in advance,
>
> Regards
> Balaji
>
>
>
> --
> You received this message because you are subscribed to the Google
> Groups "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to sqlalchemy+...@googlegroups.com
> <mailto:sqlalchemy+...@googlegroups.com>.
> To post to this group, send email to sqlal...@googlegroups.com
> <mailto:sqlal...@googlegroups.com>.
> Visit this group at https://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages