如何在SQLAlchemy中使用多个属性分配范围类型边界?

时间:2017-08-16 14:17:14

标签: postgresql sqlalchemy

我有一个名为'time_range'的PostgreSQL范围列。

CREATE table my_table (
    time_range tstzrange
);

我想把它作为两列'最早'和'最新'公开,分别定义为范围值的lower()和upper()。

我似乎可以使用hybridcolumn_property将范围值拆分为多个属性进行阅读:

from sqlalchemy Column, func
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import column_property

Base = declarative_base()

class MyClass(Base):
    __tablename__ = 'my_table'
    earliest = column_property(func.lower(Column('time_range', postgresql.TSTZRANGE())))
    latest = column_property(func.upper(Column('time_range', postgresql.TSTZRANGE())))

有没有办法定义反向写入数据库?

即。有没有办法定义类,以便在将对象写回数据库时从“最早”和“最新”属性生成范围列的值?

消费者/用户将执行以下操作:

instance = session.query(MyClass).first()
instance.earliest_timestamp = now
instance.latest_timestamp = now + timedelta(hours=2)
session.commit() 
# The value of the time_range column in the DB should be tstzrange(now, now+2hours)

0 个答案:

没有答案