1. 程式人生 > >SQLAlchemy外鍵的使用

SQLAlchemy外鍵的使用

blog mar 清晰 spa 註入 如果 語句 結構 ref

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")

SQLAlchemy外鍵的使用