如何为指向同一个表的多个外键创建多个关系?

时间:2015-03-07 19:58:03

标签: python sql sqlalchemy foreign-keys foreign-key-relationship

让我们假设以下两个MySQL表:

-- -----------------------------------------------------
-- Table `mydb`.`Person`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`Person` (
  `id` INT NOT NULL ,
  `first_name` VARCHAR(45) NOT NULL ,
  `last_name` VARCHAR(45) NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `mydb`.`Parents`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`Parents` (
  `person_id` INT NOT NULL ,
  `mother` INT NOT NULL ,
  `father` INT NOT NULL ,
  PRIMARY KEY (`person_id`) ,
  INDEX `mother_idx` (`mother` ASC) ,
  INDEX `father_fk_idx` (`father` ASC) ,
  CONSTRAINT `person_fk`
    FOREIGN KEY (`person_id` )
    REFERENCES `mydb`.`Person` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `mother_fk`
    FOREIGN KEY (`mother` )
    REFERENCES `mydb`.`Person` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `father_fk`
    FOREIGN KEY (`father` )
    REFERENCES `mydb`.`Person` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

两个表之间有3对一对多关系。

SQLAlchemy使用的模型类可以类似于:

class Person(Base)
    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)

class Parents(Base)
    person_id = Column(Integer, ForeignKey('person.id'), primary_key=True)
    mother_id = Column(Integer, ForeignKey('person.id'))
    father_id = Column(Integer, ForeignKey('person.id'))

以下是要添加到backref表的三个Parents关系:

person = relationship(Person, backref=backref('parents', uselist=True))
mother = relationship(Person, backref=backref('mothers', uselist=True))
father = relationship(Person, backref=backref('fathers', uselist=True))

不幸的是,这些关系无效;创建表时没有错误,但在尝试插入时出现以下内容:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship ...

作为SQLAlchemy的新手,我遇到了这种情况的困难。请指教。

[编辑1]

代码的小修正。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案here。关键是使用foreign_keys参数。

因此,关系可以类似于:

person = relationship(Person, backref=backref('parents', uselist=True), foreign_keys=person_id)
mother = relationship(Person, backref=backref('mothers', uselist=True), foreign_keys=mother_id)
father = relationship(Person, backref=backref('fathers', uselist=True), foreign_keys=father_id)

(我已将此作为答案添加,因为它是问题的解决方案并且有效。我不知道这是正确的方式来做事情因此,SQLAlchemy,我期待着任何其他答案/替代方案。)