Tutorial :SQLAlchemy - Models - using dynamic fields - ActiveRecord



Question:

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.


Solution:1

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.


Solution: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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »