• python3 + flask + sqlalchemy +orm(3):多对多关系


    一篇文章有多个tag,一个tag也可以属于多篇文章,文章和tag存在多对多关系

    config.py

    DEBUG = True
    #dialect+driver://root:1q2w3e4r5t@127.0.0.1:3306/
    DIALECT = 'mysql'
    DRIVER='pymysql'
    USERNAME = 'demo_user'
    PASSWORD = 'demo_123'
    HOST = '172.16.10.6'
    PORT = 3306
    DATABASE = 'db_demo1'
    
    SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    print(SQLALCHEMY_DATABASE_URI)

    app.py

    from flask import Flask
    import config
    
    from flask_sqlalchemy import SQLAlchemy
    from sqlalchemy.ext.declarative import declarative_base
    
    app = Flask(__name__)
    app.config.from_object(config)
    
    db = SQLAlchemy(app)
    Base = declarative_base()
    
    article_tag = db.Table('article_tag',
                           db.Column('article_id',db.Integer,db.ForeignKey("article.id"),primary_key=True),
                           db.Column('tag_id',db.Integer,db.ForeignKey("tag.id"),primary_key=True)
                           )
    
    class Article(db.Model):
        __tablename__='article'
        id = db.Column(db.Integer,primary_key=True,autoincrement=True)
        title = db.Column(db.String(100),nullable=True)
        tags = db.relationship('Tag',secondary=article_tag,backref=db.backref('articles'))
    
    
    class Tag(db.Model):
        __tablename__='tag'
        id = db.Column(db.Integer,primary_key=True,autoincrement=True)
        name = db.Column(db.String(100),nullable=True)
    
    db.create_all()
    
    
    @app.route('/')
    def index():
        article1 = Article(title="aaa")
        article2 = Article(title="bbb")
    
        tag1 = Tag(name='1111')
        tag2 = Tag(name='2222')
    
        article1.tags.append(tag1)
        article1.tags.append(tag2)
        article2.tags.append(tag1)
        article2.tags.append(tag2)
        db.session.add(article1)
        db.session.add(article2)
        db.session.add(tag1)
        db.session.add(tag2)
        db.session.commit()
        return 'index'
    
    
    if __name__ == '__main__':
        app.run(debug=True)
  • 相关阅读:
    [转载]datatable中只取前7条数据
    [转载]序列化的作用
    [转载]ASP.NET几种清除页面缓存的方法
    Page_Init()和page_load()区别
    [转载]回调函数
    编程规约
    语法知识【Python核心编程】
    Web基础概念扫盲
    【Tomcat源码调试-1】环境搭建(MyEclipse)
    小希的数表题解
  • 原文地址:https://www.cnblogs.com/testway/p/9936416.html
Copyright © 2020-2023  润新知