55

我有这个简单的 Author - Books 模型,但找不到将 firstName 和 lastName 设为复合键并关联使用它的方法。有任何想法吗?

from sqlalchemy import create_engine, ForeignKey, Column, String, Integer
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('mssql://user:pass@library')
engine.echo = True
session = sessionmaker(engine)()

class Author(Base):
    __tablename__ = 'authors'
    firstName = Column(String(20), primary_key=True)
    lastName = Column(String(20), primary_key=True)
    books = relationship('Book', backref='author')

class Book(Base):
    __tablename__ = 'books'
    title = Column(String(20), primary_key=True)
    author_firstName = Column(String(20), ForeignKey('authors.firstName'))
    author_lastName = Column(String(20), ForeignKey('authors.lastName'))            
4

1 回答 1

97

问题是您已经将每个依赖列分别定义为外键,当这不是您真正想要的时,您当然想要一个复合外键。Sqlalchemy 对此的回应是(以一种不太清楚的方式),它无法猜测要使用哪个外键(firstNamelastName)。

声明复合外键的解决方案在声明中有点笨拙,但仍然相当明显:

class Book(Base):
    __tablename__ = 'books'
    title = Column(String(20), primary_key=True)
    author_firstName = Column(String(20))
    author_lastName = Column(String(20))
    __table_args__ = (ForeignKeyConstraint([author_firstName, author_lastName],
                                           [Author.firstName, Author.lastName]),
                      {})

这里重要的是ForeignKey定义从各个列中消失,并将 aForeignKeyConstraint添加到__table_args__类变量中。有了这个,relationship定义的Author.books工作恰到好处。

于 2011-09-21T20:24:51.233 回答