|
| 1 | +from flask import Flask |
| 2 | +from flask_sqlalchemy import SQLAlchemy |
| 3 | +import config |
| 4 | + |
| 5 | +app = Flask(__name__) |
| 6 | +app.config.from_object(config) |
| 7 | +db = SQLAlchemy(app) |
| 8 | + |
| 9 | +class Users(db.Model): |
| 10 | + __tablename__ = 'users' |
| 11 | + id = db.Column(db.Integer, primary_key=True, autoincrement=True) |
| 12 | + username = db.Column(db.String(100), nullable=True) |
| 13 | + |
| 14 | +class Article(db.Model): |
| 15 | + __tablename__ = 'article' |
| 16 | + id = db.Column(db.Integer, primary_key=True, autoincrement=True) |
| 17 | + title = db.Column(db.String(100), nullable=True) |
| 18 | + content = db.Column(db.Text, nullable=True) |
| 19 | + author_id = db.Column(db.Integer,db.ForeignKey('users.id')) |
| 20 | + author = db.relationship('Users', backref=db.backref('articles')) |
| 21 | + |
| 22 | +db.create_all() |
| 23 | + |
| 24 | +@app.route('/') |
| 25 | +def index(): |
| 26 | + # 先添加一个新user用来添加新文章 |
| 27 | + # user1 = Users(username = 'Zac') |
| 28 | + # db.session.add(user1) |
| 29 | + # db.session.commit() |
| 30 | + |
| 31 | + # 再添加一片新文章 |
| 32 | + # article1 = Article(title = 'title1', content = 'content1', author_id = 1) |
| 33 | + # db.session.add(article1) |
| 34 | + # db.session.commit() |
| 35 | + |
| 36 | + # 找标题为aaa的作者 |
| 37 | + # 复杂方法: |
| 38 | + # article = Article.query.filter(Article.title == 'title1').first() |
| 39 | + # author_id = article.author_id |
| 40 | + # user = Users.query.filter(Users.id == author_id).first() |
| 41 | + # print(user.username) |
| 42 | + # 简单方法: |
| 43 | + # 在Article类中加入author = db.relateionship('Users', backref=db.backref('articles')) |
| 44 | + # article = Article(title = 'title1', content='content1') |
| 45 | + # article.author = Users.query.filter(Users.id == 1).first() |
| 46 | + # db.session.add(article) |
| 47 | + # db.session.commit() |
| 48 | + article = Article.query.filter(Article.title == 'title1').first() |
| 49 | + print(article.author.username) |
| 50 | + return 'index' |
| 51 | + |
| 52 | +if __name__ == '__main__': |
| 53 | + app.run(debug=True) |
0 commit comments