appleLover
appleLover

Reputation: 15691

Database Relationship - Syntax

A question on the syntax involved in SQLAlchemy.

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)

Why is it ForeignKey('child.id') and not ForeignKey("Child.id")? Why is it relationship("Child") and not relationship("child")? Is there something fundamental about how databases and SQLAlchemy work that I don't understand which is why I have to ask this question? Thanks!

Upvotes: 2

Views: 109

Answers (2)

van
van

Reputation: 76962

In general: A relationship is defined on orm level while ForeignKey represents a database model. Now, it well might be the case that sqlalchemy is smart enough to figure from from the other, but if you keep this separation in mind, you are safe.

Specifically to your question: just read the documentation. Extract below (verbatim)

argument – a mapped class, or actual Mapper instance, representing the target of the relationship.

argument may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

column – A single target column for the key relationship. A Column object or a column name as a string: tablename.columnkey or schema.tablename.columnkey. columnkey is the key which has been assigned to the column (defaults to the column name itself), unless link_to_name is True in which case the rendered name of the column is used.

Upvotes: 2

Kracekumar
Kracekumar

Reputation: 20419

relationship(Child) is also valid. By capitalising inside string, sqlalchemy will look for respective model.

Relationship isn't sql standard so SQLAlchemy is using its own convention, whereas ForeignKey is SQL Standard so tablename.column is used.

Upvotes: 2

Related Questions