I am not able to code this pattern. I read about it at many places, in
doc, FAQ and at
http://groups.google.co.in/group/sqlalchemy/browse_thread/thread/66d0094c671bd5bc,
but still could not do it. May be my noviceness. Needing help. I tried
somethings like this, but it did not help:
from sqlalchemy import *
from sqlalchemy.ext.assignmapper import assign_mapper
from sqlalchemy.ext.sessioncontext import SessionContext
context = SessionContext(create_session)
session = context.current
metadata = BoundMetaData('sqlite:///satest', echo=False)
# table definitions
person_table = Table('person', metadata,
Column('person_id', Integer, primary_key=True, autoincrement =
True),
Column('first_name', Unicode(30)),
Column('last_name', Unicode(30)))
metadata.drop_all()
metadata.create_all()
class Person(object):
@staticmethod
def Create(first_name, last_name):
p = Person(first_name=first_name, last_name=last_name)
p.CallAfterInitializationOrFetchingFromDatabase()
return p
def CallAfterInitializationOrFetchingFromDatabase(self):
self.full_name = self.first_name + ' ' + self.last_name
class PersonExtension(object):
def create_instance(self, mapper, selectcontext, row, Person):
p = Person()
p.CallAfterInitializationOrFetchingFromDatabas()
return p
assign_mapper(context, Person, person_table,
extension=PersonExtension())
p = Person.Create(first_name="Sanjay", last_name="Patel")
Assert p.full_name == "Sanjay Patel"
p.flush()
del p
session.clear()
p = Person.get_by(person_id=1)
assert p.full_name == "Sanjay Patel"
I think using __new__ might be simpler, but can't guess how exactly
to use it.
thanks
Sanjay
Needing help badly. Summarizing my problem: I need to run some
initialization code after an object is retrieved from database. Say I
have a table Person(first_name, last_name), I need that while the
object is fetched, another instance variable named full_name is
assigned as firstname + last_name.
Tried to use MapperExtension by going through the suggestions in some
threads, in the FAQ and the doc, but could not secceed. Also, could
not find out how to use __new__ in this scenario. Surely my
noviceness, either in Python or SQLAlchemy.
Some sample code or specific guidence could help a lot.
thanks
Sanjay
This was exactly what I needed. Thanks a lot!
Sanjay
(I think I wrote this message yesterday also, which did not appear.
Might have pressed the discard button?!)