Python / SQLAlchemy - loading relationship when updating a foreign key?

I have a class:

class Chart(Base):
   __tablename__ = 'chart'
   id = C('chart_id', Integer, primary_key=True)
   element_id = C(Integer, ForeignKey('element.element_id'))
   element = relationship(Element)
   name = C(String)

   def __init__(self, name):
      self.name = name

Usage is quite common,

chart = Chart('Some name')
chart.element_id = element_id

But chart.element is None after setting element_id. Is there a way to automatically load this relation for a new object before flush / commit?

+5
source share
1 answer

The best option is

chart = Chart('Some name')
chart.element = element

Assign a direct object to the ship relationship. If you assign element_id, then until it is reset, it will be in memory. Internally, it calls a request SELECT * FROM ELEMENT WHERE ELEMENT.id = element_id, but the element_id data is not stored or will be in memory.

So, I suggest a direct destination if you do not want to hide.

Hope this helps you.

+5

All Articles