SQLAlchemy:如何将混合属性设为声明属性?

发布于 2024-11-19 16:11:43 字数 2005 浏览 2 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

羅雙樹 2024-11-26 16:11:43

我还处于 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* 类方法移出该类。这样你也可以在不同的类上重用它。也许 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()

希望你明白了。

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.

彼岸花ソ最美的依靠 2024-11-26 16:11:43

我已经运行了脚本并且没问题(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'>

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'>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文