python使用alchemy处理一对一和反向引用

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config

#以上导入所需模块
app = Flask(__name__)  #实例化flask
app.config.from_object(config)#引入数据库配置
db = SQLAlchemy(app)   #实例化sqlalchemy
db.create_all()   #测试观察是否有错误

#Flask-SQLAlchemy外键及其关系
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'))
    author = db.relationship('User',backref=db.backref('articles'))


db.create_all()
@app.route('/')
def index():
    user = User.query.filter(User.username == '刘备').first()
    articles = user.articles
    for article in articles:
        print(article.title)

    return 'hello'

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

你可能感兴趣的:(python使用alchemy处理一对一和反向引用)