On Sep 18, 2008, at 6:27 AM, GHZ wrote:

>
> Hi,
>
> I have a database table : 'Child' that contains the parent_id and
> grandparent_id.  Foreign keys are present for both.
>
> I'm using declarative
>
> What is best practice to have the grandparent_id column set correctly
> when I insert?
>
> class GrandParent(Base):
>    __tablename__ = 'grandparent'
>    __table_args__ = {'autoload' : True, 'useexisting' : True}
>    children = relation('Parent', backref=backref('parents')
>
> class Parent(Base):
>    __tablename__ = 'parent'
>    __table_args__ = {'autoload' : True, 'useexisting' : True}
>    children = relation('Child', backref=backref('parents')
>
> class Child(Base):
>    # Table has parent_id and grandparent_id columns
>    __tablename__ = 'child'
>    __table_args__ = {'autoload' : True, 'useexisting' : True}
>
>
> grandparent = GrandParent()
> parent = Parent()
> child = Child()
>
> grandparent.children = [parent]
> parent.children = [child]
>
> When I flush, I want child.grandparent_id to be set to the newly
> created grandparent.


theres two general ways:

1. quick and dirty: use a before_insert()/before_update()  
MapperExtension which sets the "grandparent_id" column on Child.  If  
Child also had a relation() to GrandParent, you'd want to expire() it  
too.

2. more involved: catch change events and populate a Child.grandparent  
relation().   0.5 has made the AttributeExtension API public which  
would be a good place to catch this event.  The advantage to this is  
that your Child has a "grandparent" already set before any SQL is  
issued to the database.



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
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