zoukankan      html  css  js  c++  java
  • SQLAlchemy外键的使用

    orm可以将数据库存储的数据封装成对象,同时,如果封装的好的话,所有的数据库操作都可以封装到对象中。这样的代码在组织结构上会非常的清晰,并且相对与使用sql语句在sql注入方面会极具降低。

    SQLAlchemy中的映射关系有四种,分别是一对多,多对一,一对一,多对多

    实现这种映射关系只需要外键(ForeignKey),和relationship

    一对多:

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, CHAR
    from sqlalchemy import ForeignKey
    from sqlalchemy.orm import relationship, backref
    
    Base = declarative_base()
    
    class Parent(Base):
        __table__ = "parent"
        id = Column(Integer, Primary_key=True)
        name = Column(CHAR(50))
        child = relationship("child", backref="parent")
    
    class Child(Base):
        __table__ = "child"
        id = Column(Integer, Primary_key=True)
        name = Column(CHAR(50))
        parent_id = Column(Integer,ForeignKey('parent.id'))
    

    多对一:(建议)

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, CHAR
    from sqlalchemy import ForeignKey
    from sqlalchemy.orm import relationship, backref
    
    Base = declarative_base()
    
    class Parent(Base):
        __table__ = "parent"
        id = Column(Integer, Primary_key=True)
        name = Column(CHAR(50))
    
    class Child(Base):
        __table__ = "child"
        id = Column(Integer, Primary_key=True)
        name = Column(CHAR(50))
        parent_id = Column(Integer,ForeignKey('parent.id'))
        parent = relationship("parent", backref="child")
    

     

  • 相关阅读:
    SQLserver 逗号隔开字段分开
    css实现鼠标移动到div,改变另一个div 样式
    selenium账号密码模拟登陆豆瓣
    HTML+CSS基础
    Nginx 报错 413 Request Entity Too Large 的解决方法
    Nginx 报错 504 Gateway Time-out 的解决方法
    Object定时器
    Object标签遮挡
    winRAR打包EXE
    jqGrid API
  • 原文地址:https://www.cnblogs.com/caicairui/p/7821601.html
Copyright © 2011-2022 走看看