Why are the foreign keys in a SQLAlchemy Association Object marked as primary keys?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Cool Puzzler LoFi
--
Chapters
00:00 Question
00:57 Accepted answer (Score 5)
02:23 Thank you
--
Full question
https://stackoverflow.com/questions/4799...
Question links:
[sqlalchemy]: http://docs.sqlalchemy.org/en/latest/orm...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sqlalchemy #flasksqlalchemy
#avk47
ACCEPTED ANSWER
Score 5
This is not unique to SQLAlchemy. This is how many-to-many relationships are designed, which is based on the principles of Relational Database design.
In a many-to-many relationship, there is a need for an additional table, also called association table, which maps entries from the first table with corresponding entries from the second table.
When the association table is defined, we need some primary key to uniquely identify records in the association table. Having a primary key creates an index, which speeds up joining operations and the search for records.
So, why have all the Foreign keys as a part of the Primary for the association table?
This is to make sure there are no duplicate entries of record a of table A and record b of Table B. In other words, to ensure uniqueness in the relationship, thus, avoiding duplication of relationships.
Association table can be created without declaring the Foreign keys as Primary keys. But this is not advisable. By doing so, the join operations become slow unless indexes are created explicitly. And, there is a good chance of having duplicated records of a relationship between Table A and Table B