1

我有一个像这样的简单模型

class ChatMessage(Base):
    __tablename__ = 'chat_messages'
   id = Column(Integer, ForeignKey('messages.id'))
   sender_id = Column(Integer, ForeignKey('users.id'))
   receiver_id = Column(Integer, ForeignKey('users.id'))

我尝试添加与用户相关的消息。

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    chat_messages = relationship("ChatMessage", backref="participants",
                             foreign_keys="[ChatMessage.sender_id, ChatMessage.receiver_id]")

它给:

InvalidRequestError:一个或多个映射器无法初始化 - 无法继续初始化其他映射器。最初的例外是:无法确定关系 User.chat_messages 上的父/子表之间的连接条件 - 有多个外键路径链接表。指定“foreign_keys”参数,提供那些列的列表,这些列应该被视为包含对父表的外键引用。

4

2 回答 2

6

在创建两个类之后设置特殊关系。

import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref

engine = sa.create_engine('sqlite:///test.db', echo=True)
Session = sessionmaker(bind=engine)
Base = declarative_base(bind=engine)


class User(Base):
    __tablename__ = 'users'
    id = sa.Column(sa.Integer, primary_key=True)


class ChatMessage(Base):
    __tablename__ = 'chat_messages'
    id = sa.Column(sa.Integer, primary_key=True)
    sender_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
    receiver_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
    content = sa.Column(sa.String, nullable=False)

    __table_args__ = (
        sa.CheckConstraint(receiver_id != sender_id),
    )

    sender = relationship(User, foreign_keys=sender_id, backref='sent_chat_messages')
    receiver = relationship(User, foreign_keys=receiver_id, backref='received_chat_messages')


User.chat_messages = relationship(ChatMessage, primaryjoin=sa.or_(
    User.id == ChatMessage.sender_id,
    User.id == ChatMessage.receiver_id
), backref=backref('participants', uselist=True, viewonly=True), viewonly=True)

viewonly=True使用这种关系是因为这种关系使用自定义连接,如果数据发生更改,SQLAlchemy 将不知道该怎么做。例如,如果您附加到参与者,它会将用户添加为发送者还是接收者?

于 2013-10-12T15:55:20.000 回答
-1

看起来定义一个 primaryjoin 有点帮助,只是 append 现在不起作用

class User(Backend.instance().get_base()):

   __tablename__ = 'users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    chat_messages = relationship("ChatMessage", backref="participants",
                             primaryjoin="User.id==ChatMessage.sender_id or User.id==ChatMessage.receiver_id")
于 2013-10-12T11:02:28.070 回答