On Mar 25, 11:12 am, edgarsmolow <[email protected]> wrote:
> I have a set of interdependent tables, including accounts and persons,
> where this is their relationship (i.e., for certain persons):
>
> PK: accounts.id INT AUTO_INCREMENT
> accounts.acct_holder_id = person.id
>
> PK: person.id INT AUTO_INCREMENT
> person.account_id = account.id

You probably only want one or the other of these foreign keys. Since
an account "belongs to" a person (I'm assuming one or many accounts
per person), you can probably get rid of person.account_id. Then, in
your person class (assuming you're using the declarative approach):

from sqlalchemy.orm import relation

class Person(Base):
    __tablename__ = 'people'
    # stuff
    accounts = relation('Account')


Over in your Account class:

class Account(Base):
    __tablename__ = 'accounts'
    # stuff
    person_id = Column(Integer, ForeignKey('people'))


Then when you receive the form data, create a new person and append
the new account:

p = Person(*args, **kwargs)
p.accounts.append(Account(*args, **kwargs))
db.add(p)


Of course, I made a bunch of assumptions here, so this might not
exactly work for you. The basic idea, though, is that you need to set
up your relations properly and then what you want to do should be
fairly straightforward.


> When a new person's contact info is entered in a form, I want to add
> both the person and the account to the database.  The account is added
> first (including some fields like status):
>
> account = model.Account()
> account.status = 'P'
> db = meta.Session()
> db.add(account)
> db.commit()
>
> The account.id field will be needed to set a field on the person
> table:
> person = model.Person()
> person.first_name = 'Fred'
> person.last_name = 'Flintstone'
> person.account_id = account.id
>
> How do I then determine account.id (i.e., the last row id on the
> account table)?

In general, you should never need to take this approach.


> I could not seem to find a practical code example.

There are lots of good examples at sqlalchemy.org.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"pylons-discuss" 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/pylons-discuss?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to