两个外键连到同一张表

 have extracted the relevant parts of my model and I got to something 
that could become a FAQ item or a tutorial or an addition to the docs? 
The question is which and where? Here is the code. The one thing that 
still puzzles me is that I had to move my State table declaration 
before Policy as using "State.code" or something similar didn't work.

class State(DeclarativeBase): 
    __tablename__ = 'state'

    code = Column(String(2), primary_key=True) 
    name = Column(String(50))

class Policy(DeclarativeBase): 
    __tablename__ = 'policy'

    id = Column(Integer, primary_key=True) 
    state_of_policy_code = Column(String(2) ,ForeignKey('state.code')) 
    state_of_domicile_code = Column(String(2) ,ForeignKey('state.code')) 
    policy_state = 
relation('State',backref='state_policies',primaryjoin=state_of_policy_code= =State.code) 
    domicile_state = 
relation('State',backref='domicile_policies',primaryjoin=state_of_domicile_ code==State.code)

#test code to ran, maybe in a python shell for proper feedback. 
ny = model.State() 
ny.code = 'ny' 
fl = model.State() 
fl.code = 'fl' 
p = model.Policy() 
p.policy_state = ny 
p.domicile_state = fl 
model.save(p) 
model.DBSession.flush()#note this is TurboGears place for SQLAlchemy's 
session object. 
ny.state_policies[0].policy_state.code 

 

you can use strings with Python in them when you use declarative even 
with args like primaryjoin, so you could say things like: 

class Policy(DeclarativeBase): 
    __tablename__ = 'policy'

    policy_state = 
relation('State',backref='state_policies',primaryjoin="Policy.state_of_poli cy_code==State.code") 
    domicile_state = 
relation('State',backref='domicile_policies',primaryjoin="Policy.state_of_d omicile_code==State.code")

this would eliminate the need to have your classes in a particular 

你可能感兴趣的:(外键)