【发布时间】:2015-05-09 06:27:18
【问题描述】:
让我们假设以下两个 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'))
这是要添加到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]
对代码的小修正。
【问题讨论】:
标签: python sql sqlalchemy foreign-keys foreign-key-relationship