与父类的sqlalchemy foreignkey关系

2024-09-30 16:39:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据库架构:

父表

  1. id—主键标识符。在
  2. 类型-多态性识别。在
  3. 名称-字符串数据列。在

子表-继承父表:

  1. id—主键标识符。在
  2. parent_id-父项的外键。在
  3. 类别-字符串数据列。在

总而言之,我有两张桌子。表子级继承自父级,并且还有一个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和外键参数的关系。但错误是一样的。在

我完全不明白这个错误。 我需要帮助。在


Tags: fromimportidchildbasestringsqlalchemycreate
2条回答

您是否尝试删除子id字段的外键?在

id = Column(Integer, ForeignKey('Parent.id'), primary_key=True)
parent_id = Column(ForeignKey("Parent.id"), nullable=True)

你需要这样的东西:

^{pr2}$

我找到了解决方案here。在

SQLAlchemy在这种情况下需要一个提示:Child的映射器_args_u中的一个继承条件字段就可以做到这一点。在

# -*- 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))

  parent = relationship(Parent, foreign_keys=[parent_id])

  __mapper_args__ = {
    'polymorphic_identity':'Child',
    'inherit_condition': id == Parent.id, 
  }

engine = create_engine('postgresql+psycopg2://joe:joe@localhost/alch')

session = sessionmaker()
session.configure(bind=engine)
Base.metadata.create_all(engine)

相关问题 更多 >