Skip to main content
 首页 » 编程设计

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

2024年10月24日14unruledboy

在下面的示例中,我希望能够在 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.