码迷,mamicode.com
首页 > 数据库 > 详细

Flask-SQLAlchemy 数据库一对多

时间:2020-02-08 13:21:47      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:select   world   成功   python   run   das   primary   ons   ESS   

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 数据库一对多

标签:select   world   成功   python   run   das   primary   ons   ESS   

原文地址:https://www.cnblogs.com/hnsya/p/12275875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!