On Jan 15, 2012, at 7:46 AM, gpitel wrote:

> I am trying to setup my model initialization in two different ways.
> 1.) Initialize normally by creating an instance, e.g.,
> test0=Test0('Title')
> 2.) Initialize by query, using an input integer as the primary key,
> e.g., test0=Test(32)
> 
> This posses two questions.  Is it common practice to put a session
> inside the model? Google Code search seems to say no, but I don't see
> any other option. When I query inside the model, the attributes show
> up inside the class but not outside of it.  How do I fix this?  I have
> included some example code and output.
> 

The Session should be created externally to model objects.   The Session 
represents the *usage* of a series of models, it's not a part of the model 
itself.   A model object can refer to a session, including it's own session, 
but the scope of that session should not be defined by the model object.

In your code example, you'd construct Session right before you say "test0a = 
Test0()".   Usually, you'd do whatever queries you want here, then call add() 
or merge() as needed, outside of the model object itself.  

Here, it appears that you're attempting to create a "singleton" object out of 
Test0, that is, if someone says Test(2) and id #2 already exists, the 
constructor for Test() comes up with that identity as pulled from the Session.  
 A recipe which illustrates this pattern is at 
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject .









> Thanks for your help.
> 
> ~Grant
> 
> == CODE ==
> 
> class Test0(Base):
>    __tablename__ = 'test0'
>    id = Column(Integer, primary_key=True)
>    title = Column(String)
>    session=Session()
>    def __init__(self, *args):
>        if type(args[0])==int:
>            test=self.session.query(Test0).get(args[0])
>            self=self.session.merge(test)
>            self.session.add(self)
>        elif type(args[0])==str:
>            self.title=args[0]
>            self.session.add(self)
>    def commit(self):
>        self.session.commit()
> 
> 
> test0a=Test0('This is a test.')
> test0a.commit()
> test0b=Test0(test0a.id)
> print 'test0a title=' + str(test0a.title)
> print 'test0b title=' + str(test0b.title)
> test0b.title='CHANGED'
> test0b.commit()
> 
> == OUTPUT ==
> test0a title=This is a test.
> test0b title=None=
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to 
> [email protected].
> For more options, visit this group at 
> http://groups.google.com/group/sqlalchemy?hl=en.
> 

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to