creating new objects with references to them

J

JohnJSal

It seems like what I want to do is something that programmers deal with
everyday, but I just can't think of a way to do it. Basically, I am
writing a DB front-end and I want a new "Researcher" object to be
created whenever the user presses the "New Record" button. He can open
as many new records at a time as he wants and fill in the information.

What I don't know how to do is handle this arbitrary number of objects.
When it comes time to save the data to the DB, how do I access each
object (to get the text fields associated with each)? Won't I have to
have given each instance some name? Or is there some other way to do
this? Simply creating a new instance each time the user presses "New
Record" won't be good enough, because how do I retain a reference to
that instance over the course of the program, even after a second or
third instance has been created?

Hope that makes sense. It seems like such a common task.

Thanks.
 
S

Steve Holden

JohnJSal said:
It seems like what I want to do is something that programmers deal with
everyday, but I just can't think of a way to do it. Basically, I am
writing a DB front-end and I want a new "Researcher" object to be
created whenever the user presses the "New Record" button. He can open
as many new records at a time as he wants and fill in the information.
Seems straightforward.
What I don't know how to do is handle this arbitrary number of objects.
When it comes time to save the data to the DB, how do I access each
object (to get the text fields associated with each)? Won't I have to
have given each instance some name? Or is there some other way to do
this? Simply creating a new instance each time the user presses "New
Record" won't be good enough, because how do I retain a reference to
that instance over the course of the program, even after a second or
third instance has been created?
Start with an empty list, and append new instances to it. Then when the
user indicated completion you can iterate over the list INSERTing them
into the database (presumably INSERTing the new researcher's details first).

To minimize consistency problems it would help to make all of these
insertions as a single database transaction.
Hope that makes sense. It seems like such a common task.
regards
Steve
 
M

Marc 'BlackJack' Rintsch

JohnJSal said:
What I don't know how to do is handle this arbitrary number of objects.
When it comes time to save the data to the DB, how do I access each
object (to get the text fields associated with each)? Won't I have to
have given each instance some name? Or is there some other way to do
this? Simply creating a new instance each time the user presses "New
Record" won't be good enough, because how do I retain a reference to
that instance over the course of the program, even after a second or
third instance has been created?

Put your objects into a list. Each time the user presses the `New` Button
append a new researcher object to it.

Ciao,
Marc 'BlackJack' Rintsch
 
A

Ant

It seems like what I want to do is something that programmers deal with
everyday, but I just can't think of a way to do it. Basically, I am
writing a DB front-end and I want a new "Researcher" object to be
created whenever the user presses the "New Record" button. He can open
as many new records at a time as he wants and fill in the information.

What I don't know how to do is handle this arbitrary number of objects.
When it comes time to save the data to the DB, how do I access each
object (to get the text fields associated with each)? Won't I have to
have given each instance some name?

It all depends on what UI you are using (Web frontend? GUI such as
Tkinter?) and what your use case is.

What is it exactly that you want to do? Create a bunch of Researcher
objects and then save them in a single hit? Create a list of
Researchers and then choose which to save to the db? Populate a list of
researchers from the db, and have the option of editing or adding new
ones? Should the new Researcher objects be committed to the db as soon
as they are saved?

Anyway, a simple list of Researchers should suffice for any of these
purposes, and assuming you want to commit them all in one hit, you have
a list of objects ready to iterate over.
 
J

JohnJSal

Ant said:
It all depends on what UI you are using (Web frontend? GUI such as
Tkinter?) and what your use case is.

Making it myself with wxPython.
What is it exactly that you want to do? Create a bunch of Researcher
objects and then save them in a single hit? Create a list of
Researchers and then choose which to save to the db? Populate a list of
researchers from the db, and have the option of editing or adding new
ones? Should the new Researcher objects be committed to the db as soon
as they are saved?

There are two options: save current record and save all records, both
of which put the info in the DB immediately.

Anyway, a simple list of Researchers should suffice for any of these
purposes, and assuming you want to commit them all in one hit, you have
a list of objects ready to iterate over.

Ok, so in making a list does this mean that I won't have a name for
each instance? I just have to iterate over the list when I need them?
I'm not sure how I would do this if the user chooses just to save a
single record and not all of them.
 
S

Steve Holden

JohnJSal said:
Ant wrote:




Making it myself with wxPython.




There are two options: save current record and save all records, both
of which put the info in the DB immediately.





Ok, so in making a list does this mean that I won't have a name for
each instance? I just have to iterate over the list when I need them?
I'm not sure how I would do this if the user chooses just to save a
single record and not all of them.
Suppose you have a function dBWrite(r), where r is (some representation
of) a record you want to write into the database.

Further suppose you currently have 10 records, stored in a list rec,
with indices 0 through 9.

To write record 7 only you could use

dbWrite(rec[7])
conn.commit() # assuming dbWrite uses connection conn
del rec[7]
# you'd also want to kill the window containing this record

To write them all you might try

for r in rec:
dbWrite(r)
conn.commit()
rec = []
# Close all record windows

regards
Steve
 
J

JohnJSal

Steve said:
del rec[7]

Hmmm, but what if the record can remain open, changes can be made, and
then saved again to the same object? I suppose it isn't necessary to
delete them, right? Man, this stuff gets complicated....
 
J

JohnJSal

JohnJSal said:
Hope that makes sense. It seems like such a common task.

Ok, I'm thinking about the suggestion to make a list, but I'm still
confused. Even with a list, how do I access each instance. Would I have
to do it by index? I assume I'd do something like this:

self.records = [] # list for storing instances

Then when "New Record" is clicked:

def OnNewRecord(self, event):
self.records.append(Researchers())

But now what? There is still no reference to that instance? The only
thing I can think of is that each record will be a tab in a wxPython
notebook control, and each tab can be referenced by index. So whichever
tab I'm on, I can use that index to get that particular instance in the
list.

But this solution seems too tied to my particular implementation. How
would you normally access these instances in the list?

Let's say there are three objects in the list. Someone fills out the
text fields for the second one and clicks "Save". I know how to read
all the information in the fields, but how do I then associate it with
that second instance?

(Or I wonder if I really even need to, since upon saving, the
information gets stored in the database immediately. Maybe I don't even
need a Researcher class at all.)
 
D

Diez B. Roggisch

Ok, so in making a list does this mean that I won't have a name for
each instance? I just have to iterate over the list when I need them?
I'm not sure how I would do this if the user chooses just to save a
single record and not all of them.

It means exactly that, and where is the problem? If the user choses to
save just one record, she has to somehow select the one in question,
hasn't she? So, she selects it from the list. And then you _know_ the
index or even the record itself.

If it helps you, think of the index of the list as the name of the record...


Diez
 
S

Steve Holden

JohnJSal said:
Steve Holden wrote:

del rec[7]


Hmmm, but what if the record can remain open, changes can be made, and
then saved again to the same object? I suppose it isn't necessary to
delete them, right? Man, this stuff gets complicated....
Right. Of course, once you've written a record to the database for the
first time you need a flag to tell you it exists so that further changes
are made with UPDATE statements. But ultimately it's just a matter of
synchronizing the contents of an internal data structure with the
contents of a set of windows (typically dialogs) and a database.

Another option is to use an object-relational mapper like SQLObject or
SQLalchemy to hide most of the database ferkling.

The complexity is known as "real life". Get used to it ;-)

regards
Steve
 
S

Steve Holden

JohnJSal said:
JohnJSal wrote:

Hope that makes sense. It seems like such a common task.


Ok, I'm thinking about the suggestion to make a list, but I'm still
confused. Even with a list, how do I access each instance. Would I have
to do it by index? I assume I'd do something like this:

self.records = [] # list for storing instances

Then when "New Record" is clicked:

def OnNewRecord(self, event):
self.records.append(Researchers())

But now what? There is still no reference to that instance? The only
thing I can think of is that each record will be a tab in a wxPython
notebook control, and each tab can be referenced by index. So whichever
tab I'm on, I can use that index to get that particular instance in the
list.

But this solution seems too tied to my particular implementation. How
would you normally access these instances in the list?

Let's say there are three objects in the list. Someone fills out the
text fields for the second one and clicks "Save". I know how to read
all the information in the fields, but how do I then associate it with
that second instance?

(Or I wonder if I really even need to, since upon saving, the
information gets stored in the database immediately. Maybe I don't even
need a Researcher class at all.)
How about having a list of tuples: (record, window). Each window has to
"know" which item it's editing.

regards
Steve
 
D

Dennis Lee Bieber

self.records = [] # list for storing instances
Well, first off, using "self" here implies that /this/ is itself
part of some class... I presume part of your master GUI?
Then when "New Record" is clicked:

def OnNewRecord(self, event):
self.records.append(Researchers())

But now what? There is still no reference to that instance? The only
thing I can think of is that each record will be a tab in a wxPython
notebook control, and each tab can be referenced by index. So whichever
tab I'm on, I can use that index to get that particular instance in the
list.
And what do you do with this new record? Open a new window/tab? Pass
the record/instance to the window/tab and let IT keep track of the
record. And, just out of curiosity, how were you keeping track of these
window/tabs? In a list? No need, in my mind, to have a list of records
AND a list of windows when each window supports only one record.
But this solution seems too tied to my particular implementation. How
would you normally access these instances in the list?

Let's say there are three objects in the list. Someone fills out the
text fields for the second one and clicks "Save". I know how to read
all the information in the fields, but how do I then associate it with
that second instance?
And, again, where are these "text fields for the second one"? Does
each "record" have its own window? If so, the window "knows" which
record it controls -- you just need some way to keep track of the
windows.
(Or I wonder if I really even need to, since upon saving, the
information gets stored in the database immediately. Maybe I don't even
need a Researcher class at all.)

I'd keep it -- since the operations to load/save from the database
should probably be methods of that class -- or, at least, the mapping
from instance attributes to the SQL might be...


Try stepping back from the computer for a while... find some old 3x5
notecards, envelopes, file-folders, etc... Now try to perform your
operations using these paper objects -- creating a new researcher is
taking a clean notecard from the package... You have (in your above
example) three researcher notecards; how do you keep track of which one
is which (and if you say "I put the first one on the left, the second on
the right, and the new one is in the middle" consider that you've just
created a list that looks like [ first, new, second ]). Consider the
file folder the database... Maybe the envelopes are your window/tabs...
(if so, how are you linking envelopes and notecards? Putting the card
inside the envelope sound reasonable? Of course, you now need some way
to identify which envelope has which notecard... giving a window/tab
input focus would be the equivalent of taking the card out of the
envelope and putting it on top [making the data visible] while putting
the previous visible card back into its envelope).
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
J

John Salerno

Dennis said:
I'd keep it -- since the operations to load/save from the database
should probably be methods of that class -- or, at least, the mapping
from instance attributes to the SQL might be...

Well, I'm sort of working on a method that just involves a bunch of
functions doing all the work. Maybe not ideal. I think I need to take
your advice about stepping back and looking at it again.
 
D

Dennis Lee Bieber

Well, I'm sort of working on a method that just involves a bunch of
functions doing all the work. Maybe not ideal. I think I need to take
your advice about stepping back and looking at it again.

Just some free-association thinking here but...

class Person(object):
_INSERT_SQL = """insert into persons (name, dob, etc)
values (?, ?, ?)"""
_UPDATE_SQL = """update persons set
name = ?
dob = ?
etc = ?
where ID = ?"""
_FETCH_SQL = """select name, dob, etc from persons
where ID = ?"""
def __init__(self):
self.ID = None
self.name = None #I'm assuming no "initialized values"
self.dob = None
self.etc = None

def store(self, cursor): #I'm assuming the database connection
#and cursor are external, and passed in
cursor.begin() #or whatever starts a transaction
if self.ID:
cursor.execute(Person._UPDATE_SQL,
(self.name, self.dob, self.etc, self.ID))
else:
cursor.execute(Person._INSERT_SQL,
(self.name, self.dob, self.etc))
cursor.execute("select last_insert_id()") #adjust for DBMS
self.ID = cursor.fetchone()[0]
cursor.commit() #might want a try/except block to do rollback

def load(self,cursor):
cursor.begin()
cursor.execute(Person._FETCH_SQL, (self.ID,))
(self.name, self.dob, self.etc) = cursor.fetchone()
cursor.commit()

# Add suitable properties to control access to ID, name, dob, etc

--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top