Sqlalchemy use query views

This problem google Baidu English search in the morning. The latest answer or seven years ago. Finally, relying on their own official documents changed out a more convenient way

Use of the environment

  • python == 3.7.0
  • SQLAlchemy === 1.2.14
  • sqlacodegen === 2.0.1

Generate a view corresponding class ORM

For the first item has a data table for use sqlacodegen to quickly build a command table corresponding to the following classes

sqlacodegen --noviews --noconstraints --outfile=/root/models.py mssql+pymssql://sa:123456@locahost/test?charset=utf8

--noviews would not generate a view corresponding class here, of course want to cancel, so that the final command

sqlacodegen --noconstraints --outfile=models.py mysql+pymysql://sa:123456@locahost/test?charset=utf8

By generating a command corresponding to a view like this class ORM

metadata = Base.metadata
t_vw_test = Table(
    'vw_test', metadata,
    Column('Id', Integer),
    Column('Date',DateTime),
)

If you do not want the data table generated by sqlalchemy data table if there is no attempt here

Query View

The method of queries and query view substantially the same as ordinary table fields need only pay attention to the table obtained by columns

the userInfo DEF (Self, Goodsid): 
    RET = self.conn.query ( 
        # Get the entire row 
        sqlaclORM.t_vw_test 
        # single field acquired data 
        # sqlaclORM.t_vw_test.columns [ "a Date"] 
        # Add filter query conditions 
    ) .filter (sqlaclORM. t_vw_test.columns [ "Id"] ==. 1) .first () 
    return RET

For the return value only to the entire field of the data acquisition method to be adopted. Acquires a value corresponding to the corresponding field

# Entire row of data acquired 
date = ret.Date 
acquired for an individual subject by way of the array 

DEF the userInfo (Self, Goodsid): 
    RET = self.conn.query ( 
        Get single field data # 
        sqlaclORM.t_vw_test.columns [ "Id"] 
        sqlaclORM.t_vw_test.columns [ "a Date"] 
        # Add filter query conditions 
    ) .filter (sqlaclORM.t_vw_test.columns [ "Id"] ==. 1) .first () 
    return RET 
DATE RET = [. 1]

  

Guess you like

Origin www.cnblogs.com/lzxcloud/p/11614088.html