表名不止一次

时间:2014-02-21 06:45:48

标签: python sqlalchemy

我配置了以下表格:

class User(Base):
    __tablename__ = "user"

    id = Column(Integer, primary_key=True)
    name = Column(String)


class Gadget(Base):
    __tablename__ = "gadget"

    id = Column(Integer, primary_key=True)
    brand = Column(String)


class UserGadget(Base):
    __tablename__ = "user_gadget"

    user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    gadget_id = Column(Integer, ForeignKey('gadget.id'), primary_key=True)

    user = relationship("User", backref=backref('userGadgets', order_by=user_id))
    gadget = relationship("Gadget", backref=backref('userGadgets', order_by=gadget_id))


class GadgetComponent(Base):
    __tablename__ = "gadget_component"

    id = Column(String, primary_key=True)
    gadget_id = Column(Integer,ForeignKey('gadget.id'))
    component_maker = Column(String)

    host = relationship("Gadget", backref=backref('components', order_by=id))


class ComponentUsingMetal(Base):
    __tablename__ = "component_metal"

    id = Column(Integer, primary_key=True)    
    component_id = Column(Integer, ForeignKey('GadgetComponent.id'))  
    metal = Column(String)

    component = relationship("GadgetComponent", backref=backref('gadgetComponentMetals', order_by=id))

执行以下查询时:     session.query(User).join("userGadgets", "gadget", "components","gadgetComponentMetals").filter(ComponentUsingMetal.metal == 'iron'),component_metal附加到查询两次,给出错误'table name component_metal指定多次'。
知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

我将问题追溯到selectable.py中的以下行: froms = [f表示如果f不在toremove中,则为f)此行删除已由连接覆盖的表,以便FROM子句不会多次指定相同的表。该行没有删除component_metal,即使toremove意味着我有两个不同的Table对象用于同一个db表。然后我注意到component_metal的类ComponentUsingMetal的导入看起来不同。其他进口看起来像:

from myschema import GadgetComponent 
from myschema import Gadget
from python.myschema ComponentUsingMetal

一旦修复导入,问题就会消失。