📜  TurboGears –创建模型

📅  最后修改于: 2020-10-19 03:32:55             🧑  作者: Mango


让我们添加一个学生模型,这将在我们的sqlite数据库中建立一个学生表。

你好\你好\模型\ 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模型。在下面添加我们的学生模型。

# 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()

通过运行变速箱的setup-app命令初始化模型-

gearbox setup-app

SQLAlchemy的会话对象管理ORM对象的所有持久性操作。