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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744700053a4588724.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