1. 程式人生 > >Flask-sqlalchemy外來鍵關係對映

Flask-sqlalchemy外來鍵關係對映

本文中,為了測試方便,所以使用sqlite,定義兩張表User Article
Article中author_id引用User表中的id,也就是author_id作為User表中id的外來鍵

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./Article.db'
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'user'
id = db.Column(db.Integer,primary_key = True) username = db.Column(db.String(100),nullable = False) class Article(db.Model): __tablename__ = 'artivle' id = db.Column(db.Integer,primary_key = True) title = db.Column(db.String(100),nullable = False) content = db.Column(db.String(100
),nullable = True) #author_id引用User表中的id author_id = db.Column(db.Integer,db.ForeignKey('user.id')) # db.create_all() @app.route('/') def index(): #想要新增文章,由於依賴於使用者,所以先新增使用者 # user1 = User(username='zmy') # db.session.add(user1) # db.session.commit() #然後新增一篇文章 article = Article(title = 'today'
,content = 'hello',author_id = 1) db.session.add(article) db.session.commit() return 'index' if __name__ == '__main__': app.run()

當我們想尋找文章標題為today的作者可以用一下方式

article = Article.query.filter(Article.title =='today').first()
    user = User.query.filter(User.id == article.author_id).first()
    print(user.username)

這裡寫圖片描述

但這種方式太過於繁瑣,作為sqlalchemy可以用一下方法

class Article(db.Model):
    __tablename__ = 'article'
    id = db.Column(db.Integer,primary_key = True)
    title = db.Column(db.String(100),nullable = False)
    content = db.Column(db.String(100),nullable = True)
    #author_id引用User表中的id
    author_id = db.Column(db.Integer,db.ForeignKey('user.id'))
    #第一個引數為你要關係到哪個模型的名字,也就是類名
    #db.backref('articles')第一個引數articles為要反向引用的名字,也可以用其他名字
    #正向引用是Article訪問author,反向引用是從User訪問表Article
    author = db.relationship('User',backref=db.backref('articles'))

然後在檢視函式中

article = Article.query.filter(Article.title == 'today').first()
    print(article.author.username)

與剛才比較繁瑣的方法對比

article = Article.query.filter(Article.title =='today').first()
    user = User.query.filter(User.id == article.author_id).first()
    print(user.username)

這樣我們就可以獲取某個使用者的所有文章

user = User.query.filter(User.username == 'zmy').first()
    result = user.articles
    for article in result:
        print('-'*10)
        print(article.title)

完整程式碼

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./Article.db'
db = SQLAlchemy(app)

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

class Article(db.Model):
    __tablename__ = 'article'
    id = db.Column(db.Integer,primary_key = True)
    title = db.Column(db.String(100),nullable = False)
    content = db.Column(db.String(100),nullable = True)
    #author_id引用User表中的id
    author_id = db.Column(db.Integer,db.ForeignKey('user.id'))
    #第一個引數為你要關係到哪個模型的名字,也就是類名
    #db.backref('articles')第一個引數articles為要反向引用的名字,也可以用其他名字
    #正向引用是Article訪問author,反向引用是從User訪問表Article
    author = db.relationship('User',backref=db.backref('articles'))

#如果想新增欄位,這裡是不會做第二次對映的
#可以刪除資料庫重建,或者手動更改
db.create_all()

@app.route('/')
def index():
    #想要新增文章,由於依賴於使用者,所以先新增使用者
    # user1 = User(username='zmy')
    # db.session.add(user1)
    # db.session.commit()

    #然後新增一篇文章
    # article = Article(title = 'tomorrow',content = 'Hi',author_id = 3)
    # db.session.add(article)
    # db.session.commit()

    #想要找文章標題為today的作者
    # article = Article.query.filter(Article.title =='today').first()
    # user = User.query.filter(User.id == article.author_id).first()
    # print(user.username)

    #想找zmy寫過哪些文章
    article = Article.query.filter(Article.title == 'today').first()
    # print(article.author.username)
    #希望用author.articles的方式就能獲得zmy寫過的所有文章
    # author.articles
    # article = Article(title = 'yesterday',content = 'world')
    # article.author = User.query.filter(User.id == 1).first()

    user = User.query.filter(User.username == 'zmy').first()
    result = user.articles
    for article in result:
        print('-'*10)
        print(article.title)
    return 'index'

if __name__ == '__main__':
    app.run()