我有以下数据库架构:
父表:
子表-继承父表:
总而言之,我有两张桌子。表子级继承自父级,并且还有一个foreignkey。在
UPD:我真的需要继承和foreignkey。这个例子只是一个简短的演示,它再现了这个问题。在
我使用声明性的\u base来声明架构:
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Parent(Base):
__tablename__ = "Parent"
id = Column(Integer, primary_key=True)
type = Column(String(250))
name = Column(String(250))
__mapper_args__ = {
'polymorphic_identity':'Parent',
'polymorphic_on':type
}
class Child(Parent):
__tablename__ = 'Child'
id = Column(Integer, ForeignKey('Parent.id'), primary_key=True)
parent_id = Column(ForeignKey("Parent.id"), nullable=True)
category = Column(String(250))
__mapper_args__ = {
'polymorphic_identity':'Child',
}
engine = create_engine('postgresql+psycopg2://joe:joe@localhost/alch')
session = sessionmaker()
session.configure(bind=engine)
Base.metadata.create_all(engine)
但是当我运行代码时,我得到了以下错误:
sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'Parent' and 'Child'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
我试着自己为父母或子女分别设置关系属性,也为两者设置关系属性。尝试使用primaryjoin和外键参数的关系。但错误是一样的。在
我完全不明白这个错误。 我需要帮助。在
您是否尝试删除子id字段的外键?在
你需要这样的东西:
^{pr2}$我找到了解决方案here。在
SQLAlchemy在这种情况下需要一个提示:Child的映射器_args_u中的一个继承条件字段就可以做到这一点。在
相关问题 更多 >
编程相关推荐