views:

381

answers:

2

How close can I get to defining a model in SQLAlchemy like:

class Person(Base):  
    pass

And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something similar to RoR's ActiveRecord but in Python.

Not sure if this matters but I'll be trying to use this under IronPython rather than cPython.

+2  A: 

It is very simple to automatically pick up the field names:

from sqlalchemy import Table
from sqlalchemy.orm import MetaData, mapper

metadata = MetaData()
metadata.bind = engine

person_table = Table(metadata, "tablename", autoload=True)

class Person(object):
    pass

mapper(Person, person_table)

Using this approach, you have to define the relationships in the call to mapper(), so no auto-discovery of relationships.

To automatically map classes to tables with same name, you could do:

def map_class(class_):
    table = Table(metadata, class_.__name__, autoload=True)
    mapper(class_, table)

map_class(Person)
map_class(Order)

Elixir might do everything you want.

codeape
+1. What about auto-relationships based on naming convention - supported? good link with examples? thanks codeape
tyndall
I don't think this works for relations. These have to be defined manually in the mapper.
sebasgo
autoload=True creates the database metadata from the database scheme, and mappings for simple data fields are created automatically, but you still have to define the relations manually, because some things can't be guessed line one-to-many or one-to-one from the database layout.
sebasgo
No, this won't work for relations. But have a look at Elixir. I think it does what you need.
codeape
+2  A: 

AFAIK sqlalchemy intentionally decouples database metadata and class layout.

You may should investigate Elixir (http://elixir.ematia.de/trac/wiki): Active Record Pattern for sqlalchemy, but you have to define the classes, not the database tables.

sebasgo