sqlalchemy的relationship的基本用法


前言

国内互联网很多sqlalchemy资料搜索出来的都是老版本的操作了。新版本的sqlalchemy使用relationship相当简单,定义过来之后直接像是继承一样的方法直接用即可。

示例

from module.DB.DB import *
class RStep(Base):
    __tablename__ = 'r_step'
    ID_STEP = Column(BigInteger, nullable = False, primary_key = True)
    ID_TRANSFORMATION = Column(Integer, nullable = False)
    NAME = Column(String(255), nullable = False)
    DESCRIPTION = Column(Text(16777215), nullable = False)
    ID_STEP_TYPE = Column(Integer, ForeignKey('r_step_type.ID_STEP_TYPE'))
    DISTRIBUTE = Column(Boolean, nullable = False)
    COPIES = Column(Integer, nullable = False)
    GUI_LOCATION_X = Column(Integer, nullable = False)
    GUI_LOCATION_Y = Column(Integer, nullable = False)
    GUI_DRAW = Column(Boolean, nullable = False)
    COPIES_STRING = Column(String(255), nullable = False)
    r_step_type = relationship("RStepType")
    def __str__(self):
        info={
        'ID_STEP':self.ID_STEP,
        'ID_TRANSFORMATION':self.ID_TRANSFORMATION,
        'NAME':self.NAME,
        'DESCRIPTION':self.DESCRIPTION,
        'ID_STEP_TYPE':self.ID_STEP_TYPE,
        'DISTRIBUTE':self.DISTRIBUTE,
        'COPIES':self.COPIES,
        'GUI_LOCATION_X':self.GUI_LOCATION_X,
        'GUI_LOCATION_Y':self.GUI_LOCATION_Y,
        'GUI_DRAW':self.GUI_DRAW,
        'COPIES_STRING':self.COPIES_STRING,
        }
        info.update(self.r_step_type.toDict())
        return json.dumps(info)
    def toDict(self):
        info={
        'ID_STEP':self.ID_STEP,
        'ID_TRANSFORMATION':self.ID_TRANSFORMATION,
        'NAME':self.NAME,
        'DESCRIPTION':self.DESCRIPTION,
        'ID_STEP_TYPE':self.ID_STEP_TYPE,
        'DISTRIBUTE':self.DISTRIBUTE,
        'COPIES':self.COPIES,
        'GUI_LOCATION_X':self.GUI_LOCATION_X,
        'GUI_LOCATION_Y':self.GUI_LOCATION_Y,
        'GUI_DRAW':self.GUI_DRAW,
        'COPIES_STRING':self.COPIES_STRING,
        }
        info.update(self.r_step_type.toDict())
        return info

直接使用:

step = session.query(entity.RStep).filter(entity.RStep.ID_TRANSFORMATION == ID_TRANSFORMATION).order_by(entity.RStep.ID_STEP.asc())
data = step.frist()
print(data)

声明:一代明君的小屋|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - sqlalchemy的relationship的基本用法


欢迎来到我的小屋