0

I was going through sql alchemy and trying to understand what does back_populates does?

From this docs, we have two codes

class Parent(Base):
    __tablename__ = "parent_table"
    id = Column(Integer, primary_key=True)
    children = relationship("Child")


class Child(Base):
    __tablename__ = "child_table"
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("parent_table.id"))

and

class Parent(Base):
    __tablename__ = "parent_table"
    id = Column(Integer, primary_key=True)
    children = relationship("Child", back_populates="parent")


class Child(Base):
    __tablename__ = "child_table"
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("parent_table.id"))
    parent = relationship("Parent", back_populates="children")

Can someone explain with an example what is the difference between output of both going to be?

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • Relevant [thread](https://stackoverflow.com/questions/51335298/concepts-of-backref-and-back-populate-in-sqlalchemy) and [thread](https://stackoverflow.com/questions/39869793/when-do-i-need-to-use-sqlalchemy-back-populates). You could also just try the code with [sqlalchemy logging](https://stackoverflow.com/questions/27748053/how-to-log-sql-statements-and-rows-returned-in-sqlalchemy-to-aid-in-debugging) enabled and compare the difference yourself, and compare the difference between the `children` attribute of instances of `Parent` (along with `Child.parent`). – metatoaster Nov 21 '22 at 23:47

0 Answers0