B
B
beduin012018-04-04 17:18:55
SQL
beduin01, 2018-04-04 17:18:55

How is sqlalchemy foreign key different from relationship?

I can't figure out how foreign key differs from relationship?
It's about sqlalchemy.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Gornostaev, 2018-04-04
@beduin01

The documentation answers this question in detail:

The above class introduces the ForeignKey construct, which is a directive applied to Column that indicates that values ​​in this column should be constrained to be values ​​present in the named remote column. This is a core feature of relational databases, and is the “glue” that transforms an otherwise unconnected collection of tables to have rich overlapping relationships. The ForeignKey above expresses that values ​​in the addresses.user_id column should be constrained to those values ​​in the users.id column, ie its primary key.
A second directive, known as relationship(), tells the ORM that the Address class itself should be linked to the User class, using the attribute Address.user. relationship() uses the foreign key relationships between the two tables to determine the nature of this linkage, determining that Address.user will be many to one. An additional relationship() directive is placed on the User mapped class under the attribute User.addresses. in both relationship() directives, the parameter relationship.back_populates is assigned to refer to the complementary attribute names; by doing so, each relationship() can make an intelligent decision about the same relationship as expressed in reverse; on one side, Address.user refers to a User instance, and on the other side, User.addresses refers to a list of Address instances.

@
@microcoder, 2018-07-08
_

ForeignKey is a database entity and nothing more. RelationShip is the essence of SQLAlchemy. Based on this, you can understand that this is the difference))))
ForeignKey - Restricts from inserting other keys into the field, on which it depends on ForeignKey with another table.
RelationShip is just a convenient ORM feature that allows you to arrange inter-table relationships at the level of SQLAlchemy objects, does not affect the database in any way, works in its own area, in the context of SQLAlchemy.

A
awesomer, 2018-04-04
@awesomer

RelationShip is implemented using ForeignKey.

D
Dmitry, 2020-12-23
@Squirel_Net

https://ru.stackoverflow.com/questions/336931/%D0%...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question