1. 程式人生 > >sqlalchemy 關聯資料的新增和查詢,轉成json

sqlalchemy 關聯資料的新增和查詢,轉成json

類定義:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import MetaData, Table, Column, ForeignKey, Integer, String, Boolean, DateTime

Base = declarative_base()

#region 角色-許可權
groupRights = Table('t_db_group_rights', Base.metadata,
                    Column('groupId'
, Integer, ForeignKey('t_db_group.id')), Column('rightsId', Integer, ForeignKey('t_db_rights.id')) ) #endregion # region 使用者-角色 operatorGroup = Table('t_db_operator_group', Base.metadata, Column('operatorId', Integer, ForeignKey('t_db_operator.id'
)), Column('groupId', Integer, ForeignKey('t_db_group.id')) ) # endregion # region 使用者-許可權 operatorRights = Table('t_db_operator_rights', Base.metadata, Column('operatorId', Integer, ForeignKey('t_db_operator.id')), Column('rightsId'
, Integer, ForeignKey('t_db_rights.id')) ) # endregion #region 角色 class Group(Base): __tablename__ = 't_db_group' id = Column(Integer, primary_key=True) groupName = Column(String(30), unique=True) def toJson(self): dict = self.__dict__ rights = [] for r in self.rights: rights.append(r.toJson()) dict["rights"] = rights if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict #endregion #region 許可權 class Rights(Base): __tablename__ = 't_db_rights' id = Column(Integer, primary_key=True) rightsName = Column(String(30), nullable=False) iconCls = Column(String(30)) orderIndex = Column(Integer, default=0) fartherId = Column(Integer, default=0) urlPath = Column(String(255)) rightType = Column(Integer, default=0) needLimit = Column(Boolean, default=0) groups = relationship('Group', secondary=groupRights, backref='t_db_rights') def toJson(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict #endregion #region 操作使用者 class Operator(Base): __tablename__ ='t_db_operator' id=Column(Integer,primary_key=True) userName = Column(String(30),nullable=False,unique=True) passWord = Column(String(60),nullable=False) userType = Column(Integer,nullable=False) groups = relationship('Group',secondary = operatorGroup,backref='t_db_operator') rights = relationship('Rights',secondary = operatorRights,backref = 't_db_operator') def toJson(self): dict = self.__dict__ groups = [] for g in self.groups: groups.append(g.toJson()) dict["groups"] = groups if "_sa_instance_state" in dict: del dict["_sa_instance_state"] if "passWord" in dict: del dict["passWord"] return dict #endregion

新增操作:

from testpro import config,  modelClass
from sqlalchemy.orm import sessionmaker

if __name__ == "__main__":
    session = sessionmaker(bind=config.engine)()

    g = modelClass.Group(groupName='管理組')

    r1 = modelClass.Rights(rightsName='後臺首頁', iconCls='x-fa fa-home', orderIndex=1, fartherId=0,
                           urlPath='admindashboard',
                           rightType=1, needLimit=1)
    r2 = modelClass.Rights(rightsName='系統設定', iconCls='x-fa fa-cogs', orderIndex=2, fartherId=0,
                           urlPath='#',
                           rightType=1, needLimit=1)
    g.rights = [r1, r2]

    u = session.query(modelClass.Operator).filter_by(userName='admin').one()
    u.groups = [g]
    u.rights = g.rights
    session.commit()

查詢操作:

u = session.query(modelClass.Operator).filter_by(userName='admin').one()
print(u.toJson().__str__())