使用SqlAlchemy加入条件时出错

时间:2016-10-15 12:40:24

标签: python python-3.x sqlalchemy

我正在尝试在我的python应用程序上使用SQLAlchemy,但我遇到了多对多关系的问题。 我有4张桌子:

用户,标志,指挥官,频道和commandes_channels_flags

commandes_channels_flags包含每个相关表的外键(commandes,channels和flags)

用户也将flag_id作为外键。

所以我尝试链接commandes,channels和flag。目标是知道一个命令可以在一个标志的通道上运行。

我这样做了:

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()


class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    pseudo = Column(String(50), unique=True, nullable=False)
    flag_id = Column(ForeignKey('flags.id'))


class Flag(Base):
    __tablename__ = 'flags'

    id = Column(Integer, primary_key=True)
    irc_flag = Column(Integer)
    nom = Column(String(50))

    users = relationship("User", backref="flag", order_by="Flag.irc_flag")
    commande = relationship("Commande", secondary="commandes_channels_flags", back_populates="flags")
    channel = relationship("Channel", secondary="commandes_channels_flags", back_populates="flags")


class Channel(Base):
    __tablename__ = 'channels'

    id = Column(Integer, primary_key=True)
    uri = Column(String(50))
    topic = Column(String(255))

    commande = relationship("Commande", secondary="commandes_channels_flags", back_populates="channels")
    flag = relationship("Flag", secondary="commandes_channels_flags", back_populates="channels")


class Commande(Base):
    __tablename__ = 'commandes'

    id = Column(Integer, primary_key=True)
    pattern = Column(String(50))

    channel = relationship("Channel", secondary="commandes_channels_flags", back_populates="commandes")
    flag = relationship("Flag", secondary="commandes_channels_flags", back_populates="commandes")


class CommandeChannelFlag(Base):
    __tablename__ = 'commandes_channels_flags'

    id = Column(Integer, primary_key=True)
    commande_id = Column(ForeignKey('commandes.id'))
    channel_id = Column(ForeignKey('channels.id'))
    flag_id = Column(ForeignKey('flags.id'))

但我有这个错误:

sqlalchemy.exc.InvalidRequestError: Mapper 'Mapper|Commande|commandes' has no property 'channels'

我知道我的表链接有错误,但我找不到它。

1 个答案:

答案 0 :(得分:2)

back_populates需要匹配其他模型上相关属性的确切名称。在Channel,您有back_populates="channels",但在Commande,您有:{/ p>

channel = relationship("Channel", secondary="commandes_channels_flags", back_populates="commandes")

相反,请将channel = relationship更改为channels = relationship

您还需要将其他关系属性更改为Flag.commandesFlag.channelsChannel.commandesChannel.flagsCommande.flags以匹配您的{{ 1}}参数。