gpt4 book ai didi

python - 如何使用 SQLAlchemy 强制创建 backref InstrumentedAttributes

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:06 24 4
gpt4 key购买 nike

在下面的示例中,我希望能够在 Child 类上强制创建 parent 属性。目前,在访问定义关系的 Parent 类的 RelationshipProperty 属性之前不会创建它。

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship

Base = declarative_base()

class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship('Child', backref='parent')


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


>>> Child.parent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Child' has no attribute 'parent'
>>> Parent.children.property
<RelationshipProperty at 0x3dc3b00; children>
>>> Child.parent
<sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x0000000004718F60>

最佳答案

Citing西蒙·金:

If you want to trigger the creation of all "pending" backref attributes, I think you can call sqlalchemy.orm.configure_mappers:

Normally this gets called automatically when you start querying the database, but in certain instances you may want to call it explicitly.

关于python - 如何使用 SQLAlchemy 强制创建 backref InstrumentedAttributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32617371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com