2013-03-06 53 views
3

复合键多对多关系比方说,我有以下型号:许多与上SQLAlchemy的

class Molecule(Base): 
    db = Column(Integer, primary_key=True) 
    id = Column(Integer, primary_key=True) 
    data = Column(Integer) 

class Atom(Base): 
    id = Column(Integer, primary_key=True) 
    weight = Column(Integer) 

我要建立分子和原子之间的许多一对多关系,这将是最好的办法呢?请注意,分子的主键复合

感谢

+1

非常相似:http://stackoverflow.com/questions/10525797/sqlalchemy-relation-table-with-composite -primary-key – van 2013-03-07 10:17:15

+0

哦,你是对的,我没有看到这个问题(我也搜索过它)。无论如何,我认为我的问题和答案是更简洁,所以我会保留它们, – 2013-03-07 10:37:59

回答

6

好了,终于想通了如何做到这一点,许多一对多关系表应该是这样定义的:

molecule2atom = Table(
    'molecule2atom', 
    Base.metadata, 
    Column('molecule_db', Integer), 
    Column('molecule_id', Integer), 
    Column('atom_id', Integer, ForeignKey('atom.id')), 
    ForeignKeyConstraint( 
    ('molecule_db', 'molecule_id'), 
    ('molecule.db', 'molecule.id') ), 
) 

而且relatiohship添加到车型之一像往常一样,例如,在类原子添加:

molecules = relationship("Molecule", secondary=molecule2atom, backref="atoms") 
+0

谢谢!我只是有同样的问题,这解决了它! – Nick 2014-07-16 08:54:29