在Sqlalchemy中插入具有一对多关系的记录

时间:2018-09-27 13:35:30

标签: python sqlalchemy

我有3个tables,如下所示:

表1

class User(Base):
   __tablename__ = 'user'

   id              = Column(Integer, primary_key=True)
   uid             = Column(String(100), nullable=False, unique=True)
   fullname        = Column(String(255), nullable=False)

表2

class Message(Base):
__tablename__ = 'message'

  id              = Column(Integer, nullable=False, primary_key=True)
  uid_one         = Column(String(100), ForeignKey('user.uid'), nullable=False)
  uid_two         = Column(String(100), ForeignKey('user.uid'), nullable=False)
  ip              = Column(String(32), nullable=True)

  uidone          = relationship("User", foreign_keys="Message.uid_one", backref='uid_one')
  uidtwo          = relationship("User", foreign_keys="Message.uid_two", backref='uid_two')

表3

class Message_reply(Base):
__tablename__ = 'message_reply'

id              = Column(Integer, nullable=False, primary_key=True)
m_id            = Column(Integer, ForeignKey("message.id"), nullable=False)
uid_from        = Column(String(100), ForeignKey("user.uid"), nullable=False)
uid_to          = Column(String(100), ForeignKey("user.uid"), nullable=False)
message         = Column(Text, nullable=True)

mid             = relationship("Message", foreign_keys="Message_reply.m_id", backref='m_id')
uidfrom         = relationship("User", foreign_keys="Message_reply.uid_from", backref='uid_from')
uidto           = relationship("User", foreign_keys="Message_reply.uid_to", backref='uid_to')

如何使用一对多关系将record插入到message表和Message_reply表中?任何帮助将不胜感激!

0 个答案:

没有答案