Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy一对一和一对多同时进行(模糊ForeignKeyError)_Python_Postgresql_Orm_Sqlalchemy - Fatal编程技术网

Python SQLAlchemy一对一和一对多同时进行(模糊ForeignKeyError)

Python SQLAlchemy一对一和一对多同时进行(模糊ForeignKeyError),python,postgresql,orm,sqlalchemy,Python,Postgresql,Orm,Sqlalchemy,我正在使用SQLAlchemy,我试图在同一父类上实现一对一和一对多的关系。 这是为了便于跟踪主子实体 不幸的是,我得到了一个错误: AmbiguousForeignKeyError:无法确定之间的联接条件 关系Customer.contact上的父/子表-有 链接表的多个外键路径。指定 “foreign_keys”参数,提供以下列的列表: 应计为包含对父级的外键引用 桌子 我是做错了还是不可能 下面是一个代码示例: class Customer(Base): __tablename_

我正在使用SQLAlchemy,我试图在同一父类上实现一对一和一对多的关系。 这是为了便于跟踪主子实体

不幸的是,我得到了一个错误:

AmbiguousForeignKeyError:无法确定之间的联接条件 关系Customer.contact上的父/子表-有 链接表的多个外键路径。指定 “foreign_keys”参数,提供以下列的列表: 应计为包含对父级的外键引用 桌子

我是做错了还是不可能

下面是一个代码示例:

class Customer(Base):

    __tablename__ = 'customer'

    id = Column(Integer, primary_key=True)
    contact_id = Column(Integer, ForeignKey('contact.id'))
    address_id = Column(Integer, ForeignKey('address.id'))

    contact = relationship('Contact', backref=backref("contact", uselist=False))
    address = relationship('Address', backref=backref("address", uselist=False))

    contact_list = relationship('Contact')
    address_list = relationship('Address')


class Contact(Base):

    __tablename__ = 'contact'

    id = Column(Integer, primary_key=True)
    customer_id = Column(Integer, ForeignKey(
        'customer.id',
        use_alter=True, name='fk_contact_customer_id_customer',
        onupdate='CASCADE', ondelete='SET NULL'
    ))
    first_name = Column(String(32))
    last_name = Column(String(32))


class Address(Base):

    __tablename__ = 'address'

    id = Column(Integer, primary_key=True)
    customer_id = Column(Integer, ForeignKey(
        'customer.id',
        use_alter=True, name='fk_address_customer_id_customer',
        onupdate='CASCADE', ondelete='SET NULL'
    ))
    label = Column(String(32))

谢谢

很显然,解决方案出现在: SQLAlchemy不知道要使用哪个外键,因此必须将它们指定为
关系中的
对象(外键=[])
如下:

class Contact(Base):
    # ...
    customer_id = Column(Integer, ForeignKey(
        'customer.id',
        use_alter=True, name='fk_contact_customer_id_customer',
        onupdate='CASCADE', ondelete='SET NULL'
    ))
    # ...


class Customer(Base):
    # ...
    contact_id = Column(Integer, ForeignKey('contact.id'))
    #...
    contact = relationship('Contact', uselist=False, foreign_keys=[contact_id])
    contact_list = relationship('Contact', foreign_keys=[Contact.customer_id])
    #...