[关闭]
@bergus 2015-12-02T14:37:04.000000Z 字数 1006 阅读 1976

flask-sqlalchemy 关系表简单操作

flask python sqlalchemy


  1. from flask import Flask
  2. from flask.ext.sqlalchemy import SQLAlchemy
  3. from flask.ext.migrate import Migrate, MigrateCommand
  4. from flask.ext.script import Manager
  5. app = Flask(__name__)
  6. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
  7. db = SQLAlchemy(app)
  8. migrate = Migrate(app, db)
  9. manager = Manager(app)
  10. manager.add_command('db', MigrateCommand)
  11. class Post(db.Model):
  12. id = db.Column(db.Integer, primary_key=True)
  13. name = db.Column(db.String(80))
  14. category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
  15. category = db.relationship('Category',
  16. backref=db.backref('posts', lazy='dynamic'))
  17. class Category(db.Model):
  18. id = db.Column(db.Integer, primary_key=True)
  19. password = db.Column(db.String(50))
  20. @manager.command
  21. def run():
  22. app.debug = True
  23. app.run()
  24. if __name__ == '__main__':
  25. manager.run()
  26. # test
  27. # c1 = Category(password = 'pass1')
  28. # p1 = Post(name='name1',category=c1)
  29. # db.session.add(p1)
  30. # db.session.commit()
  31. #
  32. # p1 = db.session.query(Category).one()
  33. # print p1.id == 1
  34. # print p1.posts.one().name == 'name1'
  35. # print p1.posts.all()[0].name =='name1'
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注