SQLAlchemy外键关联使用及其详细说明

SQLAlchemy数据库增删改查 https://www.jianshu.com/p/b7704b6cb2ee
ORM是需要了解的:Object-Relational Mapping,把关系数据库的表结构映射到对象上,在Python中,ORM框架是SQLAlchemy。

这里用简单的两张表来记录SQLAlchemy数据库关联的使用。

首先创建在User模型创建了一张表,表名为“user”

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)

然后在模型Article中创建了一张名为“article”的表

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'))
    author = db.relationship('User', backref=db.backref('articles'))

这里将User中的id关联到Article中的author_id,也就是author_id就是User中的id。
关联的时候数据类型要保持一致,如db.Integer。可以通过Navicat for MySQL中的ER图标来查看。

author_id = db.Column(db.Integer, db.ForeignKey('user.id'))

这里我在User表中添加了3条数据:


10259072-a2935c0b77f5ee09.png

在Article中添加了2条数据,这两条数据是绑定在刘备下的


10259072-580de7160846934f.png

添加的代码如下:

    username = request.args.get("username")
    user = User(username=username)
    db.session.add(user)
    db.session.commit()
    title = request.args.get("title")
    content = request.args.get("content")
    aitlcle = Article(title=title, content=content, author_id=1)
    db.session.add(aitlcle)
    db.session.commit()

准备工作完成了,外键肯定是关联成功了,可以通过运行代码来查看:

查看title为“如何收复汉室?”的这个作者是谁

    article = Article.query.filter(Article.title == '如何收复汉室?').first()
    author_id = article.author_id
    user = User.query.filter(User.id == author_id).first()

下面这种写法更简单,在Article中如此:

author = db.relationship('User', backref=db.backref('articles')):

第一个参数为模型User的名字(class User),这个是正向引用, Article引用User
第二个参数为反向引用,User引用Article

# 查找刘备还写过哪些文章    正向引用  Article引用User
    article = Article.query.filter(Article.title == '如何收复汉室?').first()
    print('username:%s' % article.author.username)

上面通过正向引用,也就是Article引用User来得到title为“如何收复汉室?”的这个作者是谁,打印结果为:

username:刘备

实现了正向引用,来看看反向引用,比如刘备还发表了哪些文章,即User引用Article:

    user = User.query.filter(User.username == '刘备').first()
    articles = user.articles    #此处直接反向引用得到所有的文章
    for article in articles:
        print(article.title)

打印结果:

如何收复汉室?
等纸

Flask-SQLAlchemy外键多对多关系 https://www.jianshu.com/p/5282a7525e52

猜你喜欢

转载自blog.csdn.net/weixin_33777877/article/details/87253214