使用 sqlalchemy 组合键上的关系
我有一个简单的作者 - 书籍模型,但无法找到使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'))
I have this simple model of Author - Books and can't find a way to make firstName and lastName a composite key and use it in relation. Any ideas?
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'))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您已将每个依赖列分别定义为外键,当这不是您真正想要的时,您当然需要一个复合外键。 Sqlalchemy 对此的回应是(以一种不太清楚的方式),它无法猜测要使用哪个外键(
firstName
或lastName
)。声明复合外键的解决方案在声明上有点笨拙,但仍然相当明显:
这里重要的是
ForeignKey
定义已从各个列中消失,并且ForeignKeyConstraint
添加到__table_args__
类变量中。这样,Author.books
上定义的relationship
就可以正常工作了。The problem is that you have defined each of the dependent columns as foreign keys separately, when that's not really what you intend, you of course want a composite foreign key. Sqlalchemy is responding to this by saying (in a not very clear way), that it cannot guess which foreign key to use (
firstName
orlastName
).The solution, declaring a composite foreign key, is a tad clunky in declarative, but still fairly obvious:
The important thing here is that the
ForeignKey
definitions are gone from the individual columns, and aForeignKeyConstraint
is added to a__table_args__
class variable. With this, therelationship
defined onAuthor.books
works just right.