Hi. I am using sqlalchemy with a database that has two tables that
each have foreign keys on the other.
The situation this is modeling is a tree where the levels alternate
between two different types of node. Each Node1 has a parent of type
Node2 (or null for the root) and each Node2 has a parent of type
Node1.
(These aren't the actual names but I am trying to simplify it down for
exposition).

Using ext.declarative I have this (removing the irrelevant parts):

Base = declarative_base(metadata=metadata)

class Node1(Base):
    __tablename__ = 'node1'
    id = Column('id', Integer, primary_key=True)
    parent_node2_id = Column('parent_node2_id', Integer, ForeignKey('node2.id'))

class Node2(Base):
    __tablename__ = 'node2'
    id = Column('id', Integer, primary_key=True)
    parent_node1_id = Column('parent_node1_id', Integer, ForeignKey('node1.id'))

Node2.parent_node1 = relation(Node1, primaryjoin = Node1.id ==
Node2.parent_node1_id, backref = 'children')
Node1.parent_node2 = relation(Node2, primaryjoin = Node2.id ==
Node1.parent_node2_id, backref = 'children')

This fails (as expected) because of the circular dependency. Before I
switched to declarative, I had solved this by using a
ForeignKeyConstraint with use_alter.
I can't see how to do that with declarative. I tried changing Node2 to:

class Node2(Base):
    __tablename__ = 'node2'
    id = Column('id', Integer, primary_key=True)
    parent_node1_id = Column('parent_node1_id', Integer)
    fk = ForeignKeyConstraint(['parent_node1_id'], ['node1.guid'],
use_alter = True, name='parent_key')

SA now complains that my Node2.parent_node1 relation doesn't have a
foreign key, so it looks like the constraint didn't take.
How do I make this work?

Also, I think that I have to put the relations outside of the class
definitions (as above) because the primaryjoin arguments references
the class itself. Is there a way around this?
Thanks

--~--~---------~--~----~------------~-------~--~----~
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