SQLAlchemy:如何使hybrid_property成为declared_attr?

时间:2011-07-13 06:37:16

标签: python orm sqlalchemy declarative

我希望能够使用不同的参数调用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>

2 个答案:

答案 0 :(得分:0)

我仍然在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 * classmethod移出该类。这样你也可以在不同的类上重用它。也许 declared_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()

希望你明白这一点。

答案 1 :(得分:0)

我已经运行了脚本,它没问题(0.9.6)。您只需要更改代码:

@hybrid_property
def duration(obj):
    getattr(obj, "timestamp_%s" % end) - getattr(obj, "timestamp_%s" % start)

为:

@hybrid_property
def duration(obj):
    return getattr(obj, "timestamp_%s" % end) - getattr(obj, "timestamp_%s" % start)

结果:

duration.duration = 0:00:25.017861 datetime.timedelta(0, 25, 17861) <type 'datetime.timedelta'>