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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM