sqlalchemy orm 层面删除数据注意
Posted python成长中
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlalchemy orm 层面删除数据注意相关的知识,希望对你有一定的参考价值。
#encoding: utf-8 from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,Text, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker,relationship,backref from random import randint HOSTNAME = ‘127.0.0.1‘ PORT = 3306 DATABASE = ‘first_sqlalchemy‘ USERNAME = ‘root‘ PASSWORD = ‘123456‘ #dialect+driver://username:[email protected]:port/database DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base = declarative_base(engine) # Session = sessionmaker(engine) # session = Session() session = sessionmaker(engine)() #Session(**local_kw) class User(Base): __tablename__ = ‘user‘ id = Column(Integer,primary_key=True,autoincrement=True) username = Column(String(50),nullable=False,unique=True) class Article(Base): __tablename__ = ‘article‘ id = Column(Integer,primary_key=True,autoincrement=True) article_name = Column(String(50),nullable=False) uid = Column(Integer,ForeignKey(‘user.id‘)) author = relationship(‘User‘,backref=‘articles‘) # Base.metadata.drop_all() # # Base.metadata.create_all() #增加数据 # user = User(username=‘xiaowu‘) # # article = Article(article_name = ‘xiaoshuowang‘) # # user.articles.append(article) # # session.add(user) # session.commit() #删除表中的数据,不是说存外键关系,主表的数据是不能删除的吗? user = session.query(User).first() session.delete(user) session.commit() #一对多关系,外键约束默认是RESTRICT,父表有关联子表,数据删除不掉,为社么这里不行 #因为在orm层面没有设置uid = Column(Integer,ForeignKey(‘user.id‘)) nullable 等于False, #所以,uid设置成null,父表的主键就可以删除了 #要避免这样的结果就要这样设置,uid = Column(Integer,ForeignKey(‘user.id‘),nullable=False, #就行了
以上是关于sqlalchemy orm 层面删除数据注意的主要内容,如果未能解决你的问题,请参考以下文章