Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 218
Victor Avatar asked Oct 08 '11 18:10

Victor


People also ask

How does SQLAlchemy update data?

Update table elements in SQLAlchemy. Get the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

What does Backref do in SQLAlchemy?

backref keyword argument on the relationship() construct allows the automatic generation of a new relationship() that will be automatically be added to the ORM mapping for the related class. It will then be placed into a relationship.

What is lazy dynamic SQLAlchemy?

lazy = 'dynamic': When querying with lazy = 'dynamic', however, a separate query gets generated for the related object. If you use the same query as 'select', it will return: You can see that it returns a sqlalchemy object instead of the city objects.

What is lazy loading in SQLAlchemy?

The loading of relationships falls into three categories; lazy loading, eager loading, and no loading. Lazy loading refers to objects are returned from a query without the related objects loaded at first.


1 Answers

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.

like image 101
Nilesh Avatar answered Oct 21 '22 01:10

Nilesh