Concepts of backref and back_populate in SQLalchemy?

Solution 1:

backref is a shortcut for configuring both parent.children and child.parent relationships at one place only on the parent or the child class (not both). That is, instead of having

children = relationship("Child", back_populates="parent")  # on the parent class

and

parent = relationship("Parent", back_populates="children")  # on the child class

you only need one of this:

children = relationship("Child", backref="parent")  # only on the parent class

or

parent = relationship("Parent", backref="children")  # only on the child class

children = relationship("Child", backref="parent") will create the .parent relationship on the child class automatically. On the other hand, if you use back_populates you must explicitly create the relationships in both parent and child classes.

Why does the relationship() go inside the parent class while ForeignKey goes inside the child class?

As I said above, if you use back_populates, it needs to go on both parent and child classes. If you use backref, it needs to go on one of them only. ForeignKey needs to go on the child class, no matter where the relationship is placed, this is a fundamental concept of relational databases.

And what does having back_populates exactly do to one another?

back_populates informs each relationship about the other, so that they are kept in sync. For example if you do

p1 = Parent()
c1 = Child()
p1.children.append(c1)
print(p1.children)  # will print a list of Child instances with one element: c1
print(c1.parent)  # will print Parent instance: p1

As you can see, p1 was set as parent of c1 even when you didn't set it explicitly.

Does having the placement of which class the relationship() function exist in matter?

This only applies to backref, and no, you can place the relationship on the parent class (children = relationship("Child", backref="parent")) or on the child class (parent = relationship("Parent", backref="children")) and have the exact same effect.