@beduin01

Чем sqlalchemy foreign key отличается от relationship?

Не могу разобраться, чем foreign key отличается от relationship?
Речь про sqlalchemy.
  • Вопрос задан
  • 6581 просмотр
Решения вопроса 1
sergey-gornostaev
@sergey-gornostaev Куратор тега SQL
Седой и строгий
В документации ответ на этот вопрос подробно описан:

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, i.e. 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 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.
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 3
@microcoder
ForeignKey это сущность БД, и только. RelationShip это сущность SQLAlchemy. Исходя из этого, можно понять, что в это разница ))))
ForeignKey - Ограничивает от вставки в поле иных ключей, от которых оно зависит по ForeignKey с другой таблицей.
RelationShip - просто удобная ORM фича, позволяет устраивает межтабличные отношения на уровне объектов SQLAlchemy, никак не влияет на БД, работает в своей области, в контексте SQLAlchemy.
Ответ написан
Комментировать
@awesomer
RelationShip реализуется с помощью ForeignKey.
Ответ написан
Комментировать
@Squirel_Net
новичек
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы