Flask_sqlalchemy的增删改查

1
2
3
article = Article(title='article1', content='heihei')
db.session.add(article)
db.session.commit()

若要在新增之后获取数据库中新增数据的信息,如id

1
2
3
4
5
6
7
8
article = Article(title='article1', content='heihei')
db.session.add(article)
db.session.flush() # 添加这一条,用于预提交
db.session.commit()

# 输出新增数据的信息
print(article.id)
print(article.title)

1
2
3
4
5
6
7
8
##把需要删除的数据查找出来
article = Article.query.filter_by(content = 'heihei').first()

##把这条数据删除掉
db.session.delete(article)

##提交
db.session.commit()

1
2
3
4
5
6
7
8
##先把你要更改的数据查找出来
article = Article.query.filter(Article.title == 'article1').first()

##把这条数据需要修改的地方进行修改
article.title = 'article2'

##提交
db.session.commit()

查询单个

1
2
3
4
5
article1 = Article.query.filter(Article.title == 'article').first()
article1 = Article.query.filter_by(title = 'article').first() # 或者

print(article1.title)
print(article1.content)

查询所有

1
2
3
4
article1 = Article.query.filter_by(title = 'article').all()
for item in article1:
  print(item.title)
  print(item.content)

倒叙

1
article1 = Article.query.filter_by(title = 'article').order_by(Article.id.desc()).all()

限制数量

1
article1 = Article.query.filter_by(title = 'article').limit(10).all()
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy