python - 与 SQLAlchemy 中列的切片和转换值的关系

标签 python sqlalchemy

有没有办法分别基于 parent_idid 在父级和子级之间创建这样的关系(示例数据):

父级
Parent_id:“A1234”
姓名:“家长姓名”

child
id:1234

如何将外键添加到Childparent_id 是一个String。有没有办法对其进行切片然后转换为Integer

<小时/>

编辑: 如果情况相反怎么办:

child :
child_id:“A1234”

父级:
父字母:“A”
父 ID:1234

会是这样吗:
primaryjoin=(child_id == (Parent.parent_letter + str(Parent.parent_id)))

remote_side 会是什么样子?还是整个关系

最佳答案

参见Creating Custom Foreign Conditions文档部分。使用cast,可以为以下模型设置关系:

class Parent(Base):
    __tablename__ = 'parent'
    parent_id = Column(String, primary_key=True)
    name = Column(String, nullable=False)


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

    parent = relationship(
        Parent,
        primaryjoin=("A" + cast(id, String) == Parent.parent_id),
        foreign_keys=id,
        remote_side=Parent.parent_id,
        backref="children",
        # uselist=False,  # use in case of one-to-one relationship
    )

在这种情况下,您可以查询 Parent.childrenChild.parent:

p1 = session.query(Parent).get('A1234')
print(p1)
print(p1.children)

c1 = session.query(Child).get(1234)
print(c1)
print(c1.parent)

但是您仍然无法创建关系项目,如下所示:

p = Parent(
    parent_id='A3333', name='with a child',
    children=[Child(name='will not work')]
)
session.add(p)
session.commit()  # this will fail

Edit-1:对于您在评论和编辑中提到的替代情况,以下关系定义应该有效(显然,模型的定义也不同):

parent = relationship(
    Parent,
    primaryjoin=(
        foreign(child_id) ==
        remote(Parent.parent_letter + cast(Parent.parent_id, String))
    ),
    backref="children",
    uselist=False,
)

关于python - 与 SQLAlchemy 中列的切片和转换值的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30057446/

相关文章:

python - 列表列表的压缩列表丢失小数点

json - SqlAlchemy 与 Marshmallow 的关系

python - SQLAlchemy变量关系

python - pandas to_sql sqlalchemy 与 secure_transport 的连接

python - 从 "%H:%M:%S"创建日期时间的最佳方法是什么

python - numpy 例程似乎没有那么快

python - 如何替换 pandas 数据框中看起来相似的值?

python - 默认检查同一个表的列

python - 过滤 SQLAlchemy 关系

python: os.system不执行shell命令