当我尝试通过名称从mapper获取属性时,我无法在指定hybrid_property名称时执行此操作。
import datetime
from sqlalchemy import create_engine, MetaData
from sqlalchemy import Column, String, DateTime, Integer
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import sessionmaker
metadata = MetaData()
Base = declarative_base(metadata=metadata)
class Duration(Base):
__tablename__ = "duration"
pk = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
@hybrid_property
def duration(obj):
return obj.name
engine = create_engine('sqlite:///:memory:', echo=True)
metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
duration = Duration(name="Test")
session.add(duration)
session.commit()
print duration.__mapper__.has_property('duration') # Returns False, needs True
正如您所看到的,has_property(' duration')没有看到hybrid_property持续时间并返回False而不是True。
可以提出什么解决方案?
答案 0 :(得分:2)
虽然这里的命名质量很差,但混合不是MapperProperty,这是mapper认为的“属性”。为了适应用户想要查看特定于ORM的所有类成员而不仅仅是MapperProperty的用例,我们有all_orm_descriptors:
print "duration" in duration.__mapper__.all_orm_descriptors