开发者

Python / SQLAlchemy - load relation when foreign key is updated?

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 pretty开发者_运维知识库 common,

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

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


The best option is

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

Assign direct object to the relation ship. If you are assign element_id then until it flush it will be in memory. Internally it will fire a query SELECT * FROM ELEMENT WHERE ELEMENT.id = element_id but that element_id data is not store or it will be in memory.

So i suggest direct assign object if you don't want to flush.

Hope this will help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜