标签:char span bsp ase sql语句 操作 child column 映射关系
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")
标签:char span bsp ase sql语句 操作 child column 映射关系
原文地址:http://www.cnblogs.com/caicairui/p/7821601.html