admin管理员组文章数量:1389750
I have an sqlalchemy ORM for a Postgres table:
class Item(Base, BoilerPlateMixinBase):
id = Column(Integer, primary_key=True)
date = Column(Date)
value = Column(Float)
My project performs several SELECT queries on it.
What's the quickest way to experiment having all the dates
offset by 1 year?
I could do that by modifying either:
- the records in the table
- the lines of code that read the records
- the ORM
date
column
The latter is preferable as it'd require changing just one place in the code.
But how can this be achieved?
(tried DATEADD as suggested here, but didn't work for me. sqlalchemy 2.0)
I have an sqlalchemy ORM for a Postgres table:
class Item(Base, BoilerPlateMixinBase):
id = Column(Integer, primary_key=True)
date = Column(Date)
value = Column(Float)
My project performs several SELECT queries on it.
What's the quickest way to experiment having all the dates
offset by 1 year?
I could do that by modifying either:
- the records in the table
- the lines of code that read the records
- the ORM
date
column
The latter is preferable as it'd require changing just one place in the code.
But how can this be achieved?
(tried DATEADD as suggested here, but didn't work for me. sqlalchemy 2.0)
Share Improve this question edited Mar 13 at 21:26 EliadL asked Mar 13 at 12:48 EliadLEliadL 7,1483 gold badges29 silver badges44 bronze badges 2 |2 Answers
Reset to default 1You can also use hybrid_property
(docs):
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import Column, Integer, Date, Float, func
class Item(Base, BoilerPlateMixinBase):
id = Column(Integer, primary_key=True)
_date = Column("date", Date)
value = Column(Float)
@hybrid_property
def date(self):
return self._date.replace(year=self._date.year + 1) if self._date else None
@date.expression
def date(cls):
# in case of mysql
return func.date_add(cls._date, func.interval(1, 'year'))
# in case of postgresql
return cls._date + func.cast('1 year', Interval)
column_property
achieves this by replacing:
date = Column(Date)
with:
_date = Column('date', Date)
date = column_property(
cast(
_date + text("INTERVAL '1 YEAR'"),
Date,
).label(_date.name)
)
and it works with leap years as well.
本文标签: pythonHow to offset by 1 year the values of a date column using ORMStack Overflow
版权声明:本文标题:python - How to offset by 1 year the values of a date column using ORM? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744700052a2620510.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
DATEADD
is an SQL Server function not a Postgres one. 2) What date are you trying to modify and when do you want it modified, on INSERT or UPDATE or both? – Adrian Klaver Commented Mar 13 at 15:43DATEADD
, which doesn't seem to exist in the docs anymore. 2) The dates I'm trying to modify are all theItems.date
values, on SELECT. I'll reflect that in the question so it's clearer, thanks. – EliadL Commented Mar 13 at 21:22