Create table from declarative class definition.

128 views
Skip to first unread message

Paul Hemans

unread,
Apr 26, 2009, 2:07:52 AM4/26/09
to sqlalchemy
Hi Newbie here,
If, using the declarative style of classes, I want to create my tables
separately from actually populating them. I thought I would use
something similar to the following:

###########
from sqlalchemy import *
import time
from datetime import *
from sqlalchemy.ext.declarative import declarative_base

class CST_LEVEL(Base):
__tablename__ = 'CST_LEVEL'

REFNO = Column(String(length=10), primary_key=True)
CODE = Column(String(length=10))
DESCRIPT = Column(String(length=60))
def __init__(self, \
REFNO="", \
CODE="", \
DESCRIPT=""):
self.REFNO = REFNO
self.CODE = CODE
self.DESCRIPT = DESCRIPT

engine = create_engine('sqlite:///tutorial.db', echo=False)
metadata = MetaData()
Base = declarative_base()
metadata.create_all(engine)
###########

But this doesn't work I guess because the class never gets
instantiated. If I instantiate the class with x = CST_LEVEL() then I
would create a blank record as a by-product. How do you create the
tables, without records, using the declarative syntax?

Mike Conley

unread,
Apr 26, 2009, 7:36:48 AM4/26/09
to sqlal...@googlegroups.com
Your metadata has no knowledge of the table definition. Declarative uses a metadata instance that is a member of the Base class. Move the declaration of Base before the class definition, and either

(1) attach your metadata to Base

metadata = MetaData()
Base = declarative_base(metadata=metadata)
class CST_LEVEL(Base):
  etc...


or (2) access the internal metadata directly

Base = declarative_base()
class CST_LEVEL(Base):
  etc...
Base.metadata.create_all()


--
Mike Conley
Reply all
Reply to author
Forward
0 new messages