假设有以下两个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使用的模型类可以类似于:
^{pr2}$下面是要添加到Parents
表中的三个backref
关系:
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]
对代码做了一些小的修改。
我找到了一个解决方案here。关键是使用
foreign_keys
参数。在因此,关系可以类似于:
(我之所以加上这个作为答案,是因为这是问题的解决方案,而且很管用。我不知道这是否是SQLAlchemy中正确的方法,因此,我期待其他答案/替代方法。)
相关问题 更多 >
编程相关推荐