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

flask-sqlalchemy 关系表简单操作

时间:2015-05-23 01:11:20      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

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‘

flask-sqlalchemy 关系表简单操作

标签:

原文地址:http://www.cnblogs.com/bergus/p/4523504.html

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