BuddyJoe
BuddyJoe

Reputation: 71171

SQLAlchemy - Models - using dynamic fields - ActiveRecord

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.

Upvotes: 1

Views: 1579

Answers (2)

codeape
codeape

Reputation: 100904

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.

Upvotes: 4

sebasgo
sebasgo

Reputation: 3861

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.

Upvotes: 2

Related Questions