IWonderWhy

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

模型建立一一对多模型:

  1. 多表添加外键,建立两张表之间的关系
  2. 一表关联多表的属性,可以方便快速访问多表的数据
  3. 模板一层循环渲染一表数据,二层循环渲染多表的数据
  4. 代码展示:
    from  flask import Flask
    
    # Flask参数,可以配置静态文件路由,及文件夹
    from flask import render_template
    from flask.ext.sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@127.0.0.1:3306/test2'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    
    db = SQLAlchemy(app)
    
    class Author(db.Model):
        __tablename__ = 'author'
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(32), unique=True)
        au_book = db.relationship('Books', backref='author')
    
        def __repr__(self):
            return ("Author:%s")%self.name
    
    
    class Books(db.Model):
        __tablename__ = 'books'
        id = db.Column(db.Integer,primary_key=True)
        name = db.Column(db.String(64),unique=True)
        author_id = db.Column(db.Integer,db.ForeignKey('author.id'))
    
        def __str__(self):
            return ("Books:%s")%self.name
    
    @app.route("/books")
    def index():
        authors = Author.query.all()
    
        return render_template('books.html',authors=authors)
    
    
    if __name__ == "__main__":
        
        app.run(debug=True)

     

  5. 模板代码显示:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>图书管理</title>
    </head>
    <body>
    <h1>图书管理系统</h1>
    <br>
    <ul>
        {% for author in authors %}
            <li>{{ author.name }}</li>
            <ul>
            {% for book in author.au_book %}
                <li>{{ book.name }}</li>
                {% endfor%}
            </ul>
        {% endfor %}
    </ul>
    </body> </html>

     

  6. 渲染表单数据
    class AddBookForm(FlaskForm):
        author = StringField('作者',validators=[InputRequired('请输入作者')])
        book = StringField('书籍',validators=[InputRequired('请输入书名')])
        submit = SubmitField('添加')
    
    @app.route("/books")
    def index():
        book_author_form = AddBookForm()
        authors = Author.query.all()
    
        return render_template('books.html',authors=authors,form=book_author_form)

     

  7. 模板中渲染表单数据
    <form action="post">
        {{ form.csrf_token() }}<br>
        {{ form.author.label }}{{ form.author }}<br>
        {{ form.book.label }}{{ form.book }}<br>
        {{ form.submit }}
    </form>
    

      

 

posted on 2019-01-17 11:54  IWonderWhy  阅读(293)  评论(0编辑  收藏  举报