flask-sqlalchemy 关系表简单操作

こ雲淡風輕ζ 提交于 2019-11-29 10:43:03
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)


class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))

category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
category = db.relationship('Category',
backref=db.backref('posts', lazy='dynamic'))


class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
password = db.Column(db.String(50))


@manager.command
def run():
app.debug = True
app.run()


if __name__ == '__main__':
manager.run()

# test
# c1 = Category(password = 'pass1')
# p1 = Post(name='name1',category=c1)
# db.session.add(p1)
# db.session.commit()
#
# p1 = db.session.query(Category).one()
# print p1.id == 1
# print p1.posts.one().name == 'name1'
# print p1.posts.all()[0].name =='name1'

转载于:https://my.oschina.net/kooksee/blog/542422

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!