1

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1. What about auto-relationships based on naming convention - supported? good link with examples? thanks codeape
I don't think this works for relations. These have to be defined manually in the mapper.
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.
No, this won't work for relations. But have a look at Elixir. I think it does what you need.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.