The questions below are related to database table relationships and the abstractions which SQLAlchemy provides for it.
- What is the difference between remote and local side?
- If there is
remote_side
then why not alocal_side
? - In the example given here how is
parent_id
"local" side? remote_side
takes in alist
so what are the elements of thatlist
supposed to be? And if their are more then one elements then what exactly does that signify?
I have read the docs several time but fail to understand the basic concept behind it and how to use it appropriately. (Almost) All I know is that it is supposed to convert a one-to-many relationship into many-to-one. And usually when I try to use it, where I feel its relevant, I end introducing ambiguities which SQLAlchemy complains about, which in majority of the cases is fixed by removing the remote_side
argument all together.
given a model like:
Regarding the relationship
Parent.children
, columns that are present onParent
are thelocal
side, columns that are present onChild
are the remote side.This seems a bit trivial, and only becomes something interesting when you have a so-called "self-referential" relationship, where both sides refer to the same table:
Where above,
Parent.id
is the local side ofParent.children
andParent.parent_id
is the remote side, based onParent -> .children -> Parent
considering the left side to be "local" and the right side to be "remote".There is a local side, if you were to say Parent.children.property.local_side you'd see it.
remote_side
andlocal_side
are only things that the relationship needs to worry about, andremote_side
is public as something you can set only for the purposes of giving relationship a hint with a self referential relationship; nothing else.If you have
Node.parent
, that looks likeNode --> .parent --> Node
. "local" means the left side and "remote" is the right. The way a many-to-one self referential joins is likeNode.parent_id = Node.id
, so parent_id is local.It's a list because in SQLAlchemy all primary and foreign keys can potentially be composite, meaning, consists of more than one column. In the typical case of a surrogate key, it's a list of one element.
Overall, you should never need to use
remote_side
except in the very specific case of a self-referential relationship that is many-to-one. Otherwise it should never be needed.