设为首页 加入收藏

TOP

SQLAlchemy外键的使用
2019-09-17 18:55:24 】 浏览:17
Tags: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")

 

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇分布式系统中有关一致性的理解 下一篇领域驱动设计的基础知识总结

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目