数据库关系语法

2024-04-26 12:34:03 发布

您现在位置:Python中文网/ 问答频道 /正文

关于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)

为什么是外国人儿童id')而不是外键(“儿童id")? 为什么是关系(“孩子”)而不是关系(“孩子”)?关于数据库和SQLAlchemy是如何工作的,有什么基本的东西我不明白,这就是为什么我要问这个问题?谢谢!你知道吗


Tags: keyidchildtruebasesqlalchemy关系孩子
2条回答

通常:在orm级别定义relationship,而ForeignKey表示数据库模型。现在,很可能sqlalchemy聪明到可以从另一个中分辨出来,但是如果你记住了这种分离,你是安全的。你知道吗

特别针对您的问题:请阅读文档。摘录如下(逐字)

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.

relationship(Child)也是有效的。通过将内部字符串大写,sqlalchemy将寻找相应的模型。你知道吗

关系不是sql标准,所以SQLAlchemy使用它自己的约定,而ForeignKey是sql标准,所以使用tablename.column。你知道吗

相关问题 更多 >