国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

sqlachemy orm create or delete table

這篇具有很好參考價值的文章主要介紹了sqlachemy orm create or delete table。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

sqlacehmy? one to one? ? ------detial? to descript

?關(guān)于uselist的使用。如果你使用orm直接創(chuàng)建表關(guān)系,實際上在數(shù)據(jù)庫中是可以創(chuàng)建成多對多的關(guān)系,如果加上uselist=False 你會發(fā)現(xiàn)你的orm只能查詢出來一個,如果不要這個參數(shù)orm查詢的就是多個,一對多的關(guān)系。數(shù)據(jù)庫級別如果也要限制可以自行建立唯一鍵進行約束。

總結(jié)就是:sqlacehmy One to One 是orm級別限制

sqlacehmy 簡單創(chuàng)建實例展示:

from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime ? ?

Base = declarative_base()

engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test?charset=utf8', echo=True) ? ? class Worker(Base): ? # 表名 ? __tablename__ = 'worker' ? id = Column(Integer, primary_key=True) ? name = Column(String(50), unique=True) ? age = Column(Integer) ? birth = Column(DateTime) ? part_name = Column(String(50)) ? ? # 創(chuàng)建數(shù)據(jù)表

Base.metadata.create_all(engine)

該方法引入declarative_base模塊,生成其對象Base,再創(chuàng)建一個類Worker。一般情況下,數(shù)據(jù)表名和類名是一致的。tablename用于定義數(shù)據(jù)表的名稱,可以忽略,忽略時默認定義類名為數(shù)據(jù)表名。然后創(chuàng)建字段id、name、age、birth、part_name,最后使用Base.metadata.create_all(engine)在數(shù)據(jù)庫中創(chuàng)建對應(yīng)的數(shù)據(jù)表

數(shù)據(jù)表的刪除

刪除數(shù)據(jù)表的時候,一定要先刪除設(shè)有外鍵的數(shù)據(jù)表,也就是先刪除part,然后才能刪除worker,兩者之間涉及外鍵,這是在數(shù)據(jù)庫中刪除數(shù)據(jù)表的規(guī)則。對于兩種不同方式創(chuàng)建的數(shù)據(jù)表,刪除語句也不一樣。

Base.metadata.drop_all(engine)

part.drop(bind=engine)

part.drop(bind=engine) Base.metadata.drop_all(engine)

sqlachemy +orm + create table代碼


from sqlalchemy import Column, String, create_engine, Integer, Text
from sqlalchemy.orm import sessionmaker,declarative_base
import time


# 創(chuàng)建對象的基類:
Base = declarative_base()


# 定義User對象:
class User(Base):
    # 表的名字:
    __tablename__ = 'wokers'

    # 表的結(jié)構(gòu):
    id = Column(Integer, autoincrement=True, primary_key=True, unique=True, nullable=False)
    name = Column(String(50), nullable=False)
    sex = Column(String(4), nullable=False)
    nation = Column(String(20), nullable=False)
    birth = Column(String(8), nullable=False)
    id_address = Column(Text, nullable=False)
    id_number = Column(String(18), nullable=False)
    creater = Column(String(32))
    create_time = Column(String(20), nullable=False)
    updater = Column(String(32))
    update_time = Column(String(20), nullable=False, default=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                         onupdate=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    comment = Column(String(200))


# 初始化數(shù)據(jù)庫連接:
engine = create_engine('postgresql://postgres:name@pwd:port/dbname')  # 用戶名:密碼@localhost:端口/數(shù)據(jù)庫名

Base.metadata.create_all(bind=engine)

可級聯(lián)刪除的寫法實例?

class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    parentid = Column(Integer, ForeignKey(Parent.id, ondelete='cascade'))
    parent = relationship(Parent, backref="children")

sqlachemy 比較好用的orm介紹鏈接:https://www.cnblogs.com/DragonFire/p/10166527.html

sqlachemy的級聯(lián)刪除:

https://www.cnblogs.com/ShanCe/p/15381412.html

除了以上例子還列舉一下創(chuàng)建多對多關(guān)系實例

class UserModel(BaseModel):
    __tablename__ = "system_user"
    __table_args__ = ({'comment': '用戶表'})

    username = Column(String(150), nullable=False, comment="用戶名")
    password = Column(String(128), nullable=False, comment="密碼")
    name = Column(String(40), nullable=False, comment="姓名")
    mobile = Column(String(20), nullable=True, comment="手機號")
    email = Column(String(255), nullable=True, comment="郵箱")
    gender = Column(Integer, default=1, nullable=False, comment="性別")
    avatar = Column(String(255), nullable=True, comment="頭像")
    available = Column(Boolean, default=True, nullable=False, comment="是否可用")
    is_superuser = Column(Boolean, default=False, nullable=False, comment="是否超管")
    last_login = Column(DateTime, nullable=True, comment="最近登錄時間")
    dept_id = Column(
        BIGINT,
        ForeignKey('system_dept.id', ondelete="CASCADE", onupdate="RESTRICT"),
        nullable=True, index=True, comment="DeptID"
    )

    dept_part = relationship('DeptModel',back_populates='user_part')
    roles = relationship("RoleModel", back_populates='users', secondary=UserRolesModel.__tablename__, lazy="joined")
    positions = relationship("PositionModel", back_populates='users_obj', secondary=UserPositionModel.__tablename__, lazy="joined")


class PositionModel(BaseModel):
    __tablename__ = "system_position_management"
    __table_args__ = ({'comment': '崗位表'})
    postion_number = Column(String(50), nullable=False, comment="崗位編號")
    postion_name = Column(String(50), nullable=False, comment="崗位名稱")
    remark = Column(String(100), nullable=True, default="", comment="備注")
    positon_status = Column(Integer, nullable=False, default=0, comment="崗位狀態(tài)")
    create_user = Column(Integer, nullable=True, comment="創(chuàng)建人")
    update_user = Column(Integer, nullable=True, comment="修改人")

    users_obj = relationship("UserModel", back_populates='positions', secondary=UserPositionModel.__tablename__, lazy="joined")

class UserPositionModel(BaseModel):
    __tablename__ = "system_user_position"
    __table_args__ = ({'comment': '用戶崗位關(guān)聯(lián)表'})

    user_id = Column(
        BIGINT,
        ForeignKey("system_user.id", ondelete="CASCADE", onupdate="RESTRICT"),
        primary_key=True, comment="用戶ID"
    )
    position_id = Column(
        BIGINT,
        ForeignKey("system_position_management.id", ondelete="CASCADE", onupdate="RESTRICT"),
        primary_key=True, comment="崗位ID"
    )

以上實例是多對多關(guān)系,主要是由PositionModel進行量表之間的多對多關(guān)系的關(guān)聯(lián)

多對多關(guān)系查詢

Session=sessionmaker(bind=engine)
sessions=Session()
Userobj=sessions.query(UserModel).filter(UserModel.id == 1).first()
# Positionobj=sessions.query(PositionModel).filter(PositionModel.id == 14).first()
# Userobj.positions.append(Positionobj)
for item in Userobj.positions:
    print(item.postion_name)
sessions.commit()
sessions.close()

2個對象之間是通過relationship 關(guān)聯(lián)參數(shù)進行 append 來創(chuàng)建關(guān)系

還可以通過remove來刪除之間的關(guān)系

關(guān)于基類外鍵關(guān)系搭建

1.關(guān)系中的Mixin

在SQLAlchemy的declarative體系里面,Mixin慣用法也可以用在relationship中。relationship()函數(shù)創(chuàng)建的關(guān)系,可以用declared_attr方法,消除在復(fù)制關(guān)系及其綁定字段時可能產(chǎn)生的歧義。如下的示例,將外鍵和relationship組合在一起,這樣Foo和Bar兩個派生類,都可以被配置為通過多對一的關(guān)系關(guān)聯(lián)到Target類(譯注:目前正在做單獨使用Superset后端的定制開發(fā),會新增很多張表,似乎本節(jié)的方法可以用在模型定義上)。

class RefTargetMixin(object):
    @declared_attr
    def target_id(cls):
        return Column('target_id', ForeignKey('target.id'))

    @declared_attr
    def target(cls):
        return relationship("Target")

class Foo(RefTargetMixin, Base):
    __tablename__ = 'foo'
    id = Column(Integer, primary_key=True)

class Bar(RefTargetMixin, Base):
    __tablename__ = 'bar'
    id = Column(Integer, primary_key=True)

class Target(Base):
    __tablename__ = 'target'
    id = Column(Integer, primary_key=True)

?2.基類外鍵多表關(guān)系搭建(foreign_keys的使用)

class RefTargetMixin(object):

    @declared_attr
    def target_id(cls):
        return Column('target_id', ForeignKey('target.id'))

    @declared_attr
    def target(cls):
        return relationship("Target")

class Foo(RefTargetMixin, Base):
    __tablename__ = 'foo'
    id = Column(BIGINT, primary_key=True, autoincrement=True, unique=True, comment='主鍵ID', nullable=False)
    description = Column(Text, nullable=True, comment="備注")
    name = Column(String(40), nullable=False, comment="部門名稱")
    order = Column(Integer, nullable=False, default=1, comment="顯示排序")
    parent_id = Column(
        BIGINT,
        ForeignKey("foo.id", ondelete="CASCADE", onupdate="RESTRICT"),
        nullable=True, index=True, comment="父級部門ID"
    )
    available = Column(Boolean, nullable=False, default=True, comment="是否可用")
    # description = Column(Text, nullable=True, comment="備注")

    # user_part = relationship("UserModel", back_populates="dept_part")
    parent = relationship("Foo", foreign_keys=[parent_id], cascade='all, delete-orphan')


class Bar(RefTargetMixin, Base):
    __tablename__ = 'bar'
    id = Column(BIGINT, primary_key=True, autoincrement=True, unique=True, comment='主鍵ID', nullable=False)
    description = Column(Text, nullable=True, comment="備注")

    name = Column(String(50), nullable=False, comment="菜單名稱")
    type = Column(Integer, nullable=False, comment="菜單類型")
    icon = Column(String(50), nullable=False, default="", comment="圖標")
    order = Column(Integer, nullable=False, default=1, comment="顯示排序")
    permission = Column(String(50), nullable=False, default="", comment="權(quán)限標識")
    route_name = Column(String(50), nullable=True, comment="路由名稱")
    route_path = Column(String(50), nullable=True, comment="路由路徑")
    component_path = Column(String(50), nullable=True, comment="組件路徑")
    parent_id = Column(
        BIGINT,
        ForeignKey("bar.id", ondelete="CASCADE", onupdate="RESTRICT"),
        nullable=True, index=True, comment="父級菜單ID"
    )
    parent_name = Column(String(50), nullable=True, comment="父級菜單名稱")
    available = Column(Boolean, nullable=False, default=True, comment="是否可用")
    cache = Column(Boolean, nullable=False, default=True, comment="是否緩存")
    hidden = Column(Boolean, nullable=False, default=False, comment="是否隱藏")
    # description = Column(Text, nullable=True, comment="備注")

    parent = relationship("Bar", cascade='all, delete-orphan')
    # roles = relationship("RoleModel", back_populates='menus', secondary=RoleMenusModel.__tablename__, lazy="joined")

class Target(Base):
    __tablename__ = 'target'
    id = Column(BIGINT, primary_key=True, autoincrement=True, unique=True, comment='主鍵ID', nullable=False)
    description = Column(Text, nullable=True, comment="備注")

    username = Column(String(150), nullable=False, comment="用戶名")
    password = Column(String(128), nullable=False, comment="密碼")
    name = Column(String(40), nullable=False, comment="姓名")
    mobile = Column(String(20), nullable=True, comment="手機號")
    email = Column(String(255), nullable=True, comment="郵箱")
    gender = Column(Integer, default=1, nullable=False, comment="性別")
    avatar = Column(String(255), nullable=True, comment="頭像")
    available = Column(Boolean, default=True, nullable=False, comment="是否可用")
    is_superuser = Column(Boolean, default=False, nullable=False, comment="是否超管")
    last_login = Column(DateTime, nullable=True, comment="最近登錄時間")
    dept_id = Column(
        BIGINT,
        ForeignKey('system_dept.id', ondelete="SET NULL", onupdate="RESTRICT"),
        nullable=True, index=True, comment="部門ID"
    )

    dept = relationship('Foo')
    # roles = relationship("RoleModel", secondary=UserRolesModel.__tablename__, lazy="joined")
    # positions = relationship("PositionModel", secondary=UserPositionsModel.__tablename__, lazy="joined")

說明

sqlachemy orm create or delete table,開發(fā)語言,python,sqlachemy

關(guān)于sqlachemy 主鍵繼承問題?

class CustomMixin(TimestampMixin):
    """
    自定義公共 ORM 模型
    """

    id = Column(BIGINT, primary_key=True, autoincrement=True, unique=True, comment='主鍵ID', nullable=False)
    description = Column(Text, nullable=True, comment="備注")

    @declared_attr
    def creator_id(cls):
        return Column(
            BIGINT,
            ForeignKey("system_user.id", ondelete="SET NULL", onupdate="RESTRICT"),
            nullable=True, index=True, comment="創(chuàng)建人"
        )

    @declared_attr
    def creator(cls):
        return relationship("UserModel", foreign_keys=cls.creator_id)
class UserModel(CustomMixin, Model):
    __tablename__ = "system_user"
    __table_args__ = ({'comment': '用戶表'})

    username = Column(String(150), nullable=False, comment="用戶名")
    password = Column(String(128), nullable=False, comment="密碼")
    name = Column(String(40), nullable=False, comment="姓名")
    mobile = Column(String(20), nullable=True, comment="手機號")
    email = Column(String(255), nullable=True, comment="郵箱")
    gender = Column(Integer, default=1, nullable=False, comment="性別")
    avatar = Column(String(255), nullable=True, comment="頭像")
    available = Column(Boolean, default=True, nullable=False, comment="是否可用")
    is_superuser = Column(Boolean, default=False, nullable=False, comment="是否超管")
    last_login = Column(DateTime, nullable=True, comment="最近登錄時間")
    dept_id = Column(
        BIGINT,
        ForeignKey('system_dept.id', ondelete="SET NULL", onupdate="RESTRICT"),
        nullable=True, index=True, comment="部門ID"
    )

    dept = relationship('DeptModel', primaryjoin="UserModel.dept_id == DeptModel.id")
    roles = relationship("RoleModel", secondary=UserRolesModel.__tablename__, lazy="joined")
    positions = relationship("PositionModel", secondary=UserPositionsModel.__tablename__, lazy="joined")

關(guān)于sqlachemy 模型外鍵 relationship? ?配置scheme問題解決

?僅僅主要配置relationship relationship 關(guān)聯(lián)值

class PositionOut(Basemodel):

? ? ? ? id : int

? ? ? ? name: str

positions = PositionOut

即可!文章來源地址http://www.zghlxwxcb.cn/news/detail-821845.html

到了這里,關(guān)于sqlachemy orm create or delete table的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包