时间:2021-07-01 10:21:17 帮助过:2人阅读
创建模型
class User(Base):
__tablename__ = ‘user‘
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False)
def __repr__(self):
return f‘User(username: {self.username})‘
class Article(Base):
__tablename__ = ‘article‘
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), nullable=False)
uid = Column(Integer, ForeignKey(‘user.id‘))
author = relationship(‘User‘, backref=‘article‘)
def __repr__(self):
return f‘Article(title: {self.title})‘
Base.metadata.drop_all() # 删除所有表
Base.metadata.create_all() # 创建表
插入数据
user = User(username=‘aaa‘)
article = Article(title=‘xxxxxxx‘)
article.author = user
session.add(article)
session.commit()
写SQL删除user信息,报外键约束
使用sqlalchemy删除,成功
user = session.query(User).first()
session.delete(user)
session.commit()
可见,sqlalchemy删除时会将外键设置为null,所以为了使用外键约束,需在建表的时候,设置外键nullable=False,即不允许为空
class User(Base):
__tablename__ = ‘user‘
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False)
def __repr__(self):
return f‘User(username: {self.username})‘
class Article(Base):
__tablename__ = ‘article‘
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), nullable=False)
uid = Column(Integer, ForeignKey(‘user.id‘), nullable=False)
author = relationship(‘User‘, backref=‘article‘)
def __repr__(self):
return f‘Article(title: {self.title})‘
Base.metadata.drop_all() # 删除所有表
Base.metadata.create_all() # 创建表
user = User(username=‘aaa‘)
article = Article(title=‘xxxxxxx‘)
article.author = user
session.add(article)
session.commit()
再次删除,就会报错
user = session.query(User).first()
session.delete(user)
session.commit()
三十八:数据库之ORM层面删除数据的注意事项
标签:primary 插入 报错 username query 约束 creat 类型 ssi