数据表的外键进阶(一)


1、在数据表模型中使用relationship和backref

from exts import db
import datetime

class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(50), nullable=False)
    content = db.Column(db.Text)
    time = db.Column(db.DateTime, default=datetime.datetime.now)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relationship('User', backref='articles')

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50), unique=True, nullable=False)

2、在增加数据时可以指定两个数据之间的关系

from flask import Flask
from exts import db
from models import Article, User

app = Flask(__name__)
app.config.from_pyfile('config.py')
db.init_app(app)

@app.route('/')
def index():
    article = Article(title='title1')
    user = User(username='user1')
    article.author = user
    # 只需要增加两个数据中的一个数据
    # 另一个数据会自动增加并建立关系
    db.session.add(article) # 
    db.session.commit()
    return 'Hello World!'

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

results matching ""

    No results matching ""