TurboGears – 创建模型
让我们添加一个学生模型,它将在我们的 sqlite 数据库中设置一个学生表。
Hello\hello\model\student.py
from sqlalchemy import * from sqlalchemy.orm import mapper, relation, relation, backref from sqlalchemy import Table, ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime from hello.model import DeclarativeBase, metadata, DBSession from datetime import datetime class student(DeclarativeBase): __tablename__ = 'student' uid = Column(Integer, primary_key = True) name = Column(Unicode(20), nullable = False, default = '') city = Column(Unicode(20), nullable = False, default = '') address = Column(Unicode(100), nullable = False, default = '') pincode = Column(Unicode(10), nullable = False, default = '')
现在在 __init__.py 中的 init_model() 函数中添加此模型。此函数已包含 auth 模型。在其下方添加我们的学生模型。
# 在此处导入您的模型模块。 from hello.model.auth import User, Group, Permission from hello.model.student import student
如果您希望在设置模型时使用一些数据初始化表,请在 websetup 包中的 bootstrap.py 中添加它。在bootstrap()函数中添加如下语句。
s1 = model.student() s1.name = 'M.V.Lathkar' s1.city = 'Nanded' s1.address = 'Shivaji Nagar' s1.pincode = '431602' model.DBSession.add(s1) model.DBSession.flush() transaction.commit()
通过运行 gearbox 的 setup-app 命令初始化模型 −
gearbox setup-app
SQLAlchemy 的 Session 对象管理 ORM 对象的所有持久化操作。