2016-10-15 67 views
0

我想在我的python應用程序上使用SQLAlchemy,但我遇到了多對多關係的問題。 我有4個表:與SqlAlchemy聯接的錯誤

用戶,旗幟,commandes,渠道和commandes_channels_flags

commandes_channels_flags包含每個關注表(commandes,渠道和標誌)

的用戶外鍵具有FLAG_ID作爲外鍵也是。

所以我嘗試鏈接指揮官,頻道和國旗。目的是要知道一個命令可以在一個標誌的頻道上運行。

我這樣做:

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' 

我明白,我在我的表中的錯誤鏈接,但我不能找到它。

+0

看起來你在表名中有一個拼寫錯誤:'channel_id = Column(ForeignKey('chanels.id'))' – xli

+0

噢,是的,我改變了它,但我有另一個錯誤(消息編輯) – Tartempion34

回答

1

back_populates需要匹配另一個模型上相關屬性的確切名稱。在Channel,你有back_populates="channels",但在Commande,您有:

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

相反,改變channel = relationshipchannels = relationship

您還需要改變其他關係屬性Flag.commandesFlag.channelsChannel.commandesChannel.flagsCommande.flags以符合您back_populates參數。

+0

感謝答案。我不明白第二部分。我需要更改哪些屬性? – Tartempion34

+0

'commande'在'Flag'上的'commandes',在'Flag'上的''channels'到'channels'等等。 – xli

+0

是的,我做到了,但是當你說你還需要改變其他關係屬性,你談論第一個參數?例如:Flag: commandes = relationship(「Commande.flags」,secondary =「commandes_channels_flags」,back_populates =「flags」) – Tartempion34