#encoding:utf-8 from flask import Flask from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(100),nullable=False) password = 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")) #添加外键 # 将表Aticle与表User关联起来,实现需求: # 1、可以通过一个article 标题查找到对应的作者(username) # 2、db.backref 可以通过作者username 查找到对应作者写的所有文章 # 注意: # 1、关联的class名要用引号括起来'User' # 2、反向关联写成 backref = db.backref('articles'),引号里可以随便命名,以后就用这个名称来关联 author = db.relationship('User',backref=db.backref('articles')) db.create_all() @app.route('/') #装饰器主要作用就是为视图函数扩展需求,增加额外的功能 def hello_world(): user1 = User(username = 'zhangshan',password = '123456') user2 = User(username='lisi', password='123456') db.session.add(user1) db.session.add(user2) db.session.commit() article1 = Article(title='ruby', content='low', author_id=1) article2 = Article(title='python', content='high', author_id=1) db.session.add(article1) db.session.add(article2) db.session.commit() #查出某一篇文章的作者 article = Article.query.filter(Article.title == 'ruby').first() print article.author.username #查出某一作者所有的文章 user = User.query.filter(User.username == 'zhangshan').first() articles_1 = user.articles for article in articles_1: print '--'*10 print article.title return 'hello world' if __name__ == '__main__': app.run(debug = True)
外键关联(解决关联查询问题db.ForeignKey和db.relationship)
最新推荐文章于 2023-12-14 04:00:00 发布