这次主要整理有关数据表关联的内容还有数据模型里面的一对多
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(100), nullable=False)
class Article(db.Model):
__tablename__: 'article'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
db.create_all()
创建两张表,文章的author_id关联到用户表的id字段
- 外键语法:
- db.Column(db.Integer, db.ForeignKey('user.id')),这里最后的user表示的是表名
因为文章表与用户表相关联,所以想要添加一篇文章,需要先添加用户
# user1 = User(username='user1')
# db.session.add(user1)
# db.session.commit()
#先执行创建用户
article = Article(title='aaa', content='bbb', author_id=1)
db.session.add(article)
db.session.commit()
寻找标题为aaa文章的作者
article = Article.query.filter(Article.title == 'aaa').first()
author_id = article.author_id
user = User.query.filter(User.id == author_id).first()
print("username:", user.username)
image.png
ORM模型扩展
- 建立另一张表article2,并在里面添加字段author与User模型做关联,相当于给Article2模型添加一个author属性,可以访问这篇文章的作者数据
- backref用于定义反向引用,可以通过User模型访问此模型下的所有数据
class Article2(db.Model):
__tablename__: 'article2'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
author = db. relationship('User', backref = db.backref('articles'))
image.png
通过author字段反向调用到Article2模型的数据
article = Article2.query.filter(Article.title == 'aaa').first()
print("username:", article.author.username)
image.png
实现从user一键获取所有文章数据,这里的articles对应backref里面设置的articles
user = User.query.filter(User.username == 'user1').first()
results = user.articles
for result in results:
print("%s:%s" %(result.title, result.content))
image.png
网友评论