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物件的持久化操作。

廣告
© . All rights reserved.