Hmm, it's kind of hard to say whether the code you just posted is OK or not,
without knowing what those 2 classes represent. It kind of looks to me like
your Model class is just acting as some kind of proxy to the 'real' model,
which is in SA_Model.
If that's what your doing, then I think you're not quite getting what I was
trying to say. Let me be clear: your session object, and the logic that is
doing queries and comparing values and creating new SA_Models, **should in no
way be part of the classes that represent the actual data**!!! A lot of the
time, you only want ONE session object, and it's going to be part of your ONE
controller object.
Let me give a concrete example: (you might want to maximise your email client
so the code doesn't wrap)
class MyModel(Base):
__tablename__ = 'MyModels'
id = Column(Integer, primary_key=True)
title = Column(String)
def __init__(self, title):
self.title=title
#That is the end of the model! No more! The session *controls* the flow data,
it isn't *part* of the data!
class MyController(object):
#this class represents your actual application. At the bottom of the code
we construct one of these and run it
def __init__(self):
#this is our only session object, any data flowing between the
application and the DB must go through THIS object
self.session = session()
def run(self):
while True:
pass
#this would be some sort of message loop, processing user input etc
#these next 2 functions are event handlers, they might be called upon
button clicks or keypresses etc
def CreateNewMyModel(self, title):
newMyModel = MyModel(title)
self.session.add(newMyModel)
#you could do something with the newly created MyModel here
def GetModelByID(self, id):
model = self.session.query(MyModel).filter_by(id=id).first()
#now do something with the retrieved MyModel, you might return it or
print it or pass it to some other function
#this is how we run the application
app = MyController()
app.run()
Hopefully you can see how this is meant to work: The model is just a
representation of the data, plain and simple. The controller is responsible for
all other logic, including creating new models with some title, and retrieving
a model with some id. There's your M and C, the V (the view) is your UI, which
is going to call those last 2 functions in response to user interaction.
Do you see how the model is really DUMB? It just holds values. The controller
then is like some kind of supervisor that looks after all of the data. And the
view is just calling controller functions and displaying the model to the user.
Make sense?
-----Original Message-----
From: [email protected] [mailto:[email protected]] On
Behalf Of gpitel
Sent: Monday, 16 January 2012 1:08 PM
To: sqlalchemy
Subject: [sqlalchemy] Re: Initialize model by its primary key.
What you are saying makes perfect sense. Thank you for showing me the
light. The code below incorporates what I think you were saying and
allows me to still test it easily. Thanks again. A+++ for the
SQLAlchemy community!!!
class SA_Model(Base):
__tablename__ = 'test0'
id = Column(Integer, primary_key=True)
title = Column(String)
def __init__(self, title):
self.title=title
class Model():
def __init__(self, *args):
self.session=Session()
if type(args[0])==int:
self.instance=self.session.query(SA_Model).get(args[0])
elif type(args[0])==str:
self.instance = SA_Model(args[0])
def commit(self):
self.session.add(self.instance)
self.session.commit()
model1=Model('test1')
model1.commit()
id=model1.instance.id
del model1
model2=Model(id)
model2.instance.title='text2'
model2.commit()
On Jan 15, 8:49 pm, "Jackson, Cameron"
<[email protected]> wrote:
> In the MVC architecture, the application class I mentioned is your
> controller, and the session is part of it.
>
>
>
>
>
>
>
> -----Original Message-----
> From: [email protected] [mailto:[email protected]] On
> Behalf Of Jackson, Cameron
> Sent: Monday, 16 January 2012 12:45 PM
> To: [email protected]
> Subject: RE: [sqlalchemy] Re: Initialize model by its primary key.
>
> You are correct that an object should initialise itself, but don't take that
> to mean that Test0 should be responsible for every use case where a Test0 is
> going to be created. If you need some logic that says, for example, 'If a
> Test0 already exists with id x, then return it, otherwise create a new Test0
> with id x', then that kind of comparison and object creation should be
> managed outside the class.
>
> The philosophy behind this is that any given Test0 instance shouldn't really
> have too much control or knowledge of anything outside of its own internal
> values. Let some other object (your own application class) maintain the
> collection of objects in memory, and another object again (the session)
> control the flow of data to/from the database.
>
> Sorry, I'm not sure if I'm being clear here or if I'm rambling a bit. Does
> any of that make sense to you?
>
> -----Original Message-----
> From: [email protected] [mailto:[email protected]] On
> Behalf Of gpitel
> Sent: Monday, 16 January 2012 12:27 PM
> To: sqlalchemy
> Subject: [sqlalchemy] Re: Initialize model by its primary key.
>
> Thanks for the quick response. I am not a programmer by trade, so your
> insight is a great help.
>
> My program is split up into a model, a view, and a controller.
>
> I have been validating my model using unit testing ( from what I have
> read testing the controller and view is debatable). The reason I have
> a session inside the model, is because initialization sometimes
> depends on the existing table -> query -> session. Model
> initialization should ( I thought) remain on the model side, so one
> could easily test the model.
>
> Bayer's link/recipe was scary for a noob like me, so I may have not
> other choice but to move session outside of the model. I will post my
> example when I get it working.
>
> ~Grant
>
> On Jan 15, 6:42 pm, "Jackson, Cameron"
> <[email protected]> wrote:
> > Putting a session inside a model seems like an odd thing to want to do.
> > Changes in session A won't show up in session B until you commit() A and
> > rollback() B (which of course will destroy changes you may have made in B).
>
> > I think your Test0 constructor should just be:
>
> > def __init__(self, title='');
> > self.title = title
>
> > And then you can move the other logic out of the model:
> > class MyApplication(object):
>
> > def __init__(self):
> > self.session = Session()
>
> > def GetOrCreateTest0(id):
> > test0 = self.session.query(Test0).filter_by(id=id).first():
> > if not test0:
> > test0 = Test0()
> > self.session.add(test0)
> > return test0
>
> > I may have misunderstood exactly what you were trying to accomplish, but
> > does that help?
>
> > -----Original Message-----
> > From: [email protected] [mailto:[email protected]] On
> > Behalf Of gpitel
> > Sent: Sunday, 15 January 2012 11:46 PM
> > To: sqlalchemy
> > Subject: [sqlalchemy] Initialize model by its primary key.
>
> > 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.
>
> > 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
> > athttp://groups.google.com/group/sqlalchemy?hl=en.
>
> > -------------------------------------------------------------------------
> > DISCLAIMER: This e-mail transmission and any documents, files and
> > previous e-mail messages attached to it are private and confidential.
> > They may contain proprietary or copyright material or information that
> > is subject to legal professional privilege. They are for the use of
> > the intended recipient only. Any unauthorised viewing, use, disclosure,
> > copying, alteration, storage or distribution of, or reliance on, this
> > message is strictly prohibited. No part may be reproduced, adapted or
> > transmitted without the written permission of the owner. If you have
> > received this transmission in error, or are not an authorised recipient,
> > please immediately notify the sender by return email, delete this
> > message and all copies from your e-mail system, and destroy any printed
> > copies. Receipt by anyone other than the intended recipient should not
> > be deemed a waiver of any privilege or protection. Thales Australia
> > does not warrant or represent that this e-mail or any documents, files
> > and previous e-mail messages attached are error or virus free.
>
> > -------------------------------------------------------------------------
>
> --
> 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
> athttp://groups.google.com/group/sqlalchemy?hl=en.
>
> -------------------------------------------------------------------------
> DISCLAIMER: This e-mail transmission and any documents, files and
> previous e-mail messages attached to it are private and confidential.
> They may contain proprietary or copyright material or information that
> is subject to legal professional privilege. They are for the use of
> the intended recipient only. Any unauthorised viewing, use, disclosure,
> copying, alteration, storage or distribution of, or reliance on, this
> message is strictly prohibited. No part may be reproduced, adapted or
> transmitted without the written permission of the owner. If you have
> received this transmission in error, or are not an authorised recipient,
> please immediately notify the sender by return email, delete this
> message and all copies from your e-mail system, and destroy any printed
> copies. Receipt by anyone other than the intended recipient should not
> be deemed a waiver of any privilege or protection. Thales Australia
> does not warrant or represent that this e-mail or any documents, files
> and previous e-mail messages attached are error or virus free.
>
> -------------------------------------------------------------------------
>
> --
> 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
> athttp://groups.google.com/group/sqlalchemy?hl=en.
>
> -------------------------------------------------------------------------
> DISCLAIMER: This e-mail transmission and any documents, files and
> previous e-mail messages attached to it are private and confidential.
> They may contain proprietary or copyright material or information that
> is subject to legal professional privilege. They are for the use of
> the intended recipient only. Any unauthorised viewing, use, disclosure,
> copying, alteration, storage or distribution of, or reliance on, this
> message is strictly prohibited. No part may be reproduced, adapted or
> transmitted without the written permission of the owner. If you have
> received this transmission in error, or are not an authorised recipient,
> please immediately notify the sender by return email, delete this
> message and all copies from your e-mail system, and destroy any printed
> copies. Receipt by anyone other than the intended recipient should not
> be deemed a waiver of any privilege or protection. Thales Australia
> does not warrant or represent that this e-mail or any documents, files
> and previous e-mail messages attached are error or virus free.
>
> -------------------------------------------------------------------------
--
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.
-------------------------------------------------------------------------
DISCLAIMER: This e-mail transmission and any documents, files and
previous e-mail messages attached to it are private and confidential.
They may contain proprietary or copyright material or information that
is subject to legal professional privilege. They are for the use of
the intended recipient only. Any unauthorised viewing, use, disclosure,
copying, alteration, storage or distribution of, or reliance on, this
message is strictly prohibited. No part may be reproduced, adapted or
transmitted without the written permission of the owner. If you have
received this transmission in error, or are not an authorised recipient,
please immediately notify the sender by return email, delete this
message and all copies from your e-mail system, and destroy any printed
copies. Receipt by anyone other than the intended recipient should not
be deemed a waiver of any privilege or protection. Thales Australia
does not warrant or represent that this e-mail or any documents, files
and previous e-mail messages attached are error or virus free.
-------------------------------------------------------------------------
--
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.