【问题标题】:Ambiguous column name with join query in Flask-SQLAlchemyFlask-SQLAlchemy 中带有连接查询的不明确列名
【发布时间】:2021-08-18 11:53:13
【问题描述】:

表设置:

我的列名不明确?...在​​我的第一个表中,sqlalchemy 加入的列不存在。

但是,在sqlite浏览器中,已经建立了关系。

class Parent:
    childs = db.relationship('Child',
                                   backref=db.backref('parent', lazy='joined'),
                                   lazy='select',
                                   )
class Child:
     parents = db.column(db.Integer, db.ForeignKey='parents.id')
     siblings = db.relationship('Sibling', backref=db.backref'child', lazy='select')

class Sibling:
     childs = db.column(db.Integer, db.ForeignKey='child.id')

查询:

def json_join():
   data = db.session.query(Parent, Child, Sibling)\
    .join(Parent)\
    .join(Child)\
    .join(Sibling)\
    .filter(Parent.id == Child.id == Sibling.id)\
    .all()
   return data

错误: 不明确的列名 child.id

我认为: 父列中的关系不会为子关系创建列?所以没有加入...

【问题讨论】:

    标签: python flask-sqlalchemy


    【解决方案1】:

    查看文档以了解父子关系的一对多关系: https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html#many-to-one

    class Parent(Base):
        __tablename__ = 'parent'
        id = Column(Integer, primary_key=True)
        child_id = Column(Integer, ForeignKey('child.id'))
        child = relationship("Child", back_populates="parents")
    
    class Child(Base):
        __tablename__ = 'child'
        id = Column(Integer, primary_key=True)
        parents = relationship("Parent", back_populates="child")
    

    另请参阅有关儿童和兄弟姐妹(作为父母和儿童)的多对多关系的文档:https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html#many-to-many

    association_table = Table('association', Base.metadata,
        Column('left_id', Integer, ForeignKey('left.id')),
        Column('right_id', Integer, ForeignKey('right.id'))
    )
    
    class Parent(Base):
        __tablename__ = 'left'
        id = Column(Integer, primary_key=True)
        children = relationship(
            "Child",
            secondary=association_table,
            back_populates="parents")
    
    class Child(Base):
        __tablename__ = 'right'
        id = Column(Integer, primary_key=True)
        parents = relationship(
            "Parent",
            secondary=association_table,
            back_populates="children")
    

    【讨论】:

    • 谢谢,我确实读过这个。但是flask-SQLAlchemy和SQLAlchemy的语法有区别吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2015-03-10
    • 2019-07-22
    相关资源
    最近更新 更多