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()函数中添加此模型。此函数中已经包含身份验证模型。在它下面添加我们的学生模型。

# Import your model modules here.
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的会话对象管理ORM对象的持久化操作。

广告