#定义模型 class User(db.Model): __table_name__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(200),nullable=False) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer,primary_key=True,autoincrement=True) title = db.Column(db.String(200),nullable=False) content = db.Column(db.Text,nullable=False) #外键 author_id = db.Column(db.Integer,db.ForeignKey('user.id')) #关系 #第一个参数是模型名,User 第二个参数代代反向引用,即对方访问我的时候使用的字段名称 author = db.relationship("User",backref = "articles") # db.drop_all() 删所有表 db.create_all() @app.route('/otm') def one_to_many(): art = Article(title="111",content='111111111111111111111111111111111111111111111') user = User(username="zhiliao") art.author = user db.session.add(art) db.session.commit() return "一对多数据操作成功"
增加删改查操作:
# 添加数据 # article = Article(title = "如何炼成钢",content = "把炼钢用生铁放入炼钢炉内熔炼,再把钢液浇铸成型,冷却后即得到钢锭或连铸或直接铸成各种铸钢件等" ) # db.session.add(article) # # db.session.commit() # 读取数据 # art = Article.query.filter_by(id=1)[0] # print(art.title) # 修改 # art = Article.query.filter_by(id=1)[0] # art.title="XXXXXXXX" # db.session.commit() # 删除 # art = Article.query.filter_by(id=1).delete() # db.session.commit()