On Oct 31, 2010, at 3:08 PM, Daniel Meier wrote:

> Hi list
> 
> I have tried the examples in the ORM tutorial and I'm wondering how I
> can separate different models into own modules.
> 
> Let's say I have a "BankAccount" model and a "BankCustomer" model. My
> idea would be to create two modules, bankaccount.py and
> bankcustomer.py, and a database handler that imports the necessary
> stuff from that modules.
> 
> This is what I came up with: http://pastie.org/1262474
> 
> Actually, it doesn't work because the database was not yet initiated
> (metadata.create_all). Where should I put that? Or is my idea of
> splitting up a bad one?
> 
> Daniel

I also like to keep my models separated in separate Python modules, although if 
there are closely related tables (such as a header and a detail table), I keep 
them in the same module. The "trick" is to have them all inherit from the same 
declarative_base class.  I do this by simply having a separate module that 
creates that class:

base.py
======

from sqlalchemy.ext.declarative import declarative_base
BASE = declarative_base()

======

I then import BASE into the individual modules that create the models. 

I have discovered that when calling create_all(), it's only necessary to import 
the model module and the declarative_base class files before doing the import 
and create_all() will create all the tables that are imported. This is 
convenient for creating temporary databases (I use SQLite in-memory databases 
for testing).

create_test_database.py
===================

from name import Name
from system import System
from base import BASE

engine = create_engine('sqlite://')
BASE.metadata.create_all(bind=engine)

# populate with test data

====================

In my actual application there are many more tables, but for this instance of 
testing, I only need the tables modeled by Name and System.

I hope this helps.
Mark

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to