Flask-SQLAlchemy 数据库一对多
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask-SQLAlchemy 数据库一对多相关的知识,希望对你有一定的参考价值。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config
app = Flask(__name__)
app.config.from_object(config)
db=SQLAlchemy(app)
class Writer(db.Model):
__tablename__=‘writer‘
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(50),nullable=False)
books = db.relationship(‘Book‘,backref=‘writers‘)
class Book(db.Model):
__tablename__=‘books‘
id=db.Column(db.Integer,primary_key=True)
title=db.Column(db.String(50),nullable=False)
publishing_office=db.Column(db.String(100),nullable=False)
isbn = db.Column(db.String(50),nullable=False)
writer_id = db.Column(db.Integer,db.ForeignKey(‘writer.id‘))
db.create_all()
@app.route(‘/add‘)
def add():
user1 = Writer(name=‘李兴华‘)
user2 = Writer(name=‘Sweigart‘)
db.session.add(user1)
db.session.add(user2)
book1 = Book(title=‘名师讲坛——java开发实战经典(第2版)‘,publishing_office=‘清华大学出版社‘,
isbn=‘9787302483663‘,writer_id=‘1‘)
book2=Book(title=‘android开发实战‘,publishing_office=‘清华大学出版社‘,
isbn=‘9787302483663‘,writer_id=‘1‘)
book3=Book(title=‘Python游戏编程‘,publishing_office=‘人民邮电大学出版社‘,
isbn=‘9787151466419‘,writer_id=‘2‘)
db.session.add(book1)
db.session.add(book2)
db.session.add(book3)
db.session.commit()
return ‘数据添加成功‘
@app.route(‘/select‘)
def select():
writer = Writer.query.filter(Writer.id==‘1‘).first()
book = writer.books
for k in book:
print(k)
print(k.title)
book=Book.query.filter(Book.id==‘1‘).first()
writer=book.writers
print(writer.name)
return ‘查询数据成功‘
@app.route(‘/‘)
def hello_world():
return "Hello world!"
if __name__ == ‘__main__‘:
app.run()
以上是关于Flask-SQLAlchemy 数据库一对多的主要内容,如果未能解决你的问题,请参考以下文章
Flask 学习-84.Flask-SQLAlchemy 一对多关系级联删除
Flask 学习-84.Flask-SQLAlchemy 一对多关系级联删除
flask-sqlalchemy 一对一,一对多,多对多操作