Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a parents children through a backref attribute via sqlalchemy relationship causes unnecessary flush

I have a sqlalchemy relationship like this (trimmed for simplicity):

class Parent(Base):
  __tablename__ = 'Parent'
  name = Column(String, nullable=False)
  def __init__(self, name)
    self.name = name

class Child(Base):
  __tablename__ = 'Child'
    name = Column(String, nullable=False)
    parent = relationship(Parent, backref=backref('children')
  def __init__(self, name, parent)
    self.name = name
    self.parent = parent

While working while my objects i do:

parent = Parent("my parent")
db_session.add(parent) # must be done for other reasons not relevant to the issue.
child = Child("my child", parent)

So far so good. But prior to committing when I do the following I get a DB flush:

children = parent.children # using the backref causes a flush

Can this be avoided by changing how I define the backref/relationship?

like image 649
Andrew Avatar asked Oct 02 '22 12:10

Andrew


1 Answers

Using the Session.no_autoflush context manager should achieve what you want in a safe manner:

with session.no_autoflush:    
    parent = Parent("my parent")
    db_session.add(parent) 
    child = Child("my child", parent)
like image 113
benselme Avatar answered Oct 07 '22 19:10

benselme