SQLAlchemy: How to make a hybrid_property a declared_attr?
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 Duratio开发者_Go百科n(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>
I'm still at 0.6 so I can't try your fancy properties. :)
But instead of
class Duration(Base):
# [...]
@declared_attr
def duration(cls):
return cls.create_duration_field("initiated", "done")
you could try something like:
class Duration(Base):
duration = declared_attr(create_duration_field("initiated", "done"))
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:
def constructor(**kw):
"""Creates a class constructor class method"""
def load(cls):
query = cls.query
return query.filter_by(**kw).one()
return classmethod(load)
You would use it like this:
class SomeModel(Base):
SomeInstance = constructor(primary_key=17)
instance = SomeModel.SomeInstance()
Hope you get the idea.
I've run the script and it's ok (0.9.6). You just need to change the code from:
@hybrid_property
def duration(obj):
getattr(obj, "timestamp_%s" % end) - getattr(obj, "timestamp_%s" % start)
to:
@hybrid_property
def duration(obj):
return getattr(obj, "timestamp_%s" % end) - getattr(obj, "timestamp_%s" % start)
Result:
duration.duration = 0:00:25.017861 datetime.timedelta(0, 25, 17861) <type 'datetime.timedelta'>
精彩评论