SQLAlchemy:如何将混合属性设为声明属性?
我希望能够使用不同的参数调用 Duration.create_duration_field()
,并在我的类上创建多个 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>
I would like to be able to call Duration.create_duration_field()
with different parameters and have more than one hybrid_property
created on my class. The only difference would be that different timestamps will be subtracted for each of them.
Of course using declarative_attr
is not a requirement, but I need the properties to be hybrid_property
s.
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)
Currently duration.duration
is a reference to hybrid_property
<sqlalchemy.ext.hybrid.hybrid_property object at 0x1d02190>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我还处于 0.6,所以我无法尝试你的奇特特性。 :)
但
您可以尝试以下操作:
并将您的 *create_duration_field* 类方法移出该类。这样你也可以在不同的类上重用它。也许 declared_attr 也应该移到 *create_duration_field* 内,您必须在那里进行实验。
一个例子是我一直使用的这个小东西:
你会像这样使用它:
希望你明白了。
I'm still at 0.6 so I can't try your fancy properties. :)
But instead of
you could try something like:
and move your *create_duration_field* classmethod off that class. That way you can also reuse it on different classes. Perhaps declared_attr should also be moved inside *create_duration_field*, you'll have to experiment there.
An example would be this little thing I use all the time:
You would use it like this:
Hope you get the idea.
我已经运行了脚本并且没问题(0.9.6)。您只需要将代码从: 更改
为:
结果:
I've run the script and it's ok (0.9.6). You just need to change the code from:
to:
Result: