一篇文章有多个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)