English 中文(简体)
TurboGears - Creating Models
  • 时间:2024-12-22

TurboGears – Creating Models


Previous Page Next Page  

Let us add a student model which will set up a student table in our sqpte database.

Hellohellomodelstudent.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 =   )

Now add this model in init_model() function inside __init__.py. This function already contains the auth model in it. Add our student model below it.

# Import your model modules here.
from hello.model.auth import User, Group, Permission
from hello.model.student import student

If you want the table to be initiapzed with some data at the time of setting up the models, add it in bootstrap.py in websetup package. Add the following statements in the bootstrap() function.

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

The Models are initiapzed by running setup-app command of gearbox −

gearbox setup-app

Session object of SQLAlchemy manages all persistence operations of ORM object.

Advertisements