我希望能够使用不同的参数调用Duration.create_duration_field()
,并在我的 class 中创建多个hybrid_property
。唯一的区别是将为每个时间戳减去不同的时间戳。
当然不是必须使用declarative_attr
,但是我需要将属性设置为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)
notes = Column(String)
timestamp_initiated = Column(DateTime,
default=datetime.datetime.now(),
nullable=False)
timestamp_done = Column(DateTime)
def __unicode__(self):
return self.name
@declared_attr
def duration(cls):
return cls.create_duration_field("initiated", "done")
@classmethod
def create_duration_field(cls, start, end):
@hybrid_property
def duration(obj):
getattr(obj, "timestamp_%s" % end) - getattr(obj, "timestamp_%s" % start)
@duration.expression
def duration(cls):
return getattr(cls, "timestamp_%s" % end) - getattr(cls, "timestamp_%s" % start)
return duration
engine = create_engine('sqlite:///:memory:', echo=True)
metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
duration = Duration(name="Test", timestamp_done=datetime.datetime.now() + datetime.timedelta(seconds=25))
session.add(duration)
session.commit()
assert isinstance(duration.duration, datetime.timedelta)
当前
duration.duration
是对hybrid_property
的引用<sqlalchemy.ext.hybrid.hybrid_property object at 0x1d02190>
最佳答案
我仍然是0.6,所以我无法尝试您喜欢的物业。 :)
但是代替
class Duration(Base):
# [...]
@declared_attr
def duration(cls):
return cls.create_duration_field("initiated", "done")
您可以尝试以下方法:
class Duration(Base):
duration = declared_attr(create_duration_field("initiated", "done"))
并将* create_duration_field *类方法从该类中移出。这样,您还可以在不同的类上重用它。也许clarified_attr 也应该移动到* create_duration_field *内,您必须在那里进行实验。
一个例子就是我一直使用的这个小东西:
def constructor(**kw):
"""Creates a class constructor class method"""
def load(cls):
query = cls.query
return query.filter_by(**kw).one()
return classmethod(load)
您可以这样使用它:
class SomeModel(Base):
SomeInstance = constructor(primary_key=17)
instance = SomeModel.SomeInstance()
希望你明白。
关于python - SQLAlchemy:如何使hybrid_property成为clarified_attr?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6674980/