Is it possible to fill a SQLalchemy foreign key in a model and have it load the related object

后端 未结 1 1494
眼角桃花
眼角桃花 2021-01-21 04:48

In SQLAlchemy, I have a transactionlog model, that has a related member. This relation is defined by a tlog_ppl_id c

相关标签:
1条回答
  • 2021-01-21 05:37

    If I understood you correctly, then you might be looking for load_on_pending, though its use is discouraged:

    The load_on_pending flag does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before a flush proceeds. This flag is not not intended for general use.

    Note that all in all in your test function the newly created T instance is not added to a session before attempting to print the related People instance, so it simply cannot do any loading (unless some magic is at play and all new model instances are added to some default session).

    Here's a little demo of how you perhaps could use the load_on_pending option, though I think you really should just use the instance objects instead of the foreign keys:

    In [8]: class A(Base):
       ...:     __tablename__ = 'a'
       ...:     a_id = Column(Integer, primary_key=True)
    
    In [9]: class B(Base):
       ...:     __tablename__ = 'b'
       ...:     b_id = Column(Integer, primary_key=True, autoincrement=True)
       ...:     a_id = Column(Integer, ForeignKey('a.a_id'))
       ...:     a = relationship('A', load_on_pending=True)
    
    In [10]: class C(Base):
        ...:     __tablename__ = 'c'
        ...:     C_id = Column(Integer, primary_key=True, autoincrement=True)
        ...:     a_id = Column(Integer, ForeignKey('a.a_id'))
        ...:     a = relationship('A')
    
    In [16]: session.add(A(a_id=1))
    
    In [17]: session.commit()
    
    In [18]: b = B()
    
    In [19]: session.add(b)
    
    In [20]: b.a_id = 1
    
    In [21]: b.a
    Out[21]: <__main__.A at 0x7ff32388ab70>
    
    In [22]: session.rollback()
    
    In [23]: c = C()
    
    In [25]: session.add(c)
    
    In [26]: c.a_id = 1
    
    In [27]: c.a
    
    In [28]: session.commit()
    
    In [29]: c.a
    Out[29]: <__main__.A at 0x7ff32388ab70>
    

    But, as stated before, the recommended approach would be to use the instances, not the foreign keys:

    # Will look the instance up in the session's identity map, if present
    T.member = session.query(People).get('2433...')
    

    I think that the Zen of Python applies in this case:

    Explicit is better than implicit.

    I.e. explicitly query for the to-be-related object instead of relying on implicit lookup after setting the foreign key.

    0 讨论(0)
提交回复
热议问题