Skip to content

Commit 75883ab

Browse files
committed
use generated column instead
1 parent e996608 commit 75883ab

File tree

2 files changed

+5
-26
lines changed

2 files changed

+5
-26
lines changed

nowcasting_datamodel/models/forecast.py

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
JSON,
1717
Boolean,
1818
Column,
19+
Computed,
1920
DateTime,
2021
Float,
2122
ForeignKey,
@@ -105,26 +106,6 @@ def create_partition(
105106
return super().__new__(cls, clsname, bases, attrs)
106107

107108

108-
def default_horizon_minutes(context):
109-
"""Make a default horizon minutes for the ForecastValueSQLMixin"""
110-
columns = context.get_current_parameters()
111-
target_time = columns["target_time"]
112-
created_utc = columns["created_utc"]
113-
114-
if created_utc is None:
115-
created_utc = datetime.now(tz=timezone.utc)
116-
117-
if isinstance(target_time, str):
118-
target_time = datetime.fromisoformat(target_time)
119-
120-
# make sure they both have tz, or not
121-
if target_time.tzinfo is None:
122-
created_utc = created_utc.replace(tzinfo=None)
123-
124-
delta = (target_time - created_utc).total_seconds() / 60.0 # convert to minutes
125-
return delta
126-
127-
128109
class ForecastValueSQLMixin(CreatedMixin):
129110
"""One Forecast of generation at one timestamp
130111
@@ -142,14 +123,11 @@ class ForecastValueSQLMixin(CreatedMixin):
142123
# we want to store the forecast horizon.
143124
# This is the difference between target_time and created_utc.
144125
# By storing the value queries should be faster when looking for an N hour forecast.
145-
# I tried to use
146-
# server_default = "CAST(EXTRACT(EPOCH FROM (target_time - created_utc))/60 as INT)"
147-
# but this does not work.
148126
horizon_minutes = Column(
149127
Integer,
150-
nullable=True,
128+
Computed("CAST(EXTRACT(EPOCH FROM target_time - created_utc)/60 as INT)"),
129+
nullable=False,
151130
index=True,
152-
default=default_horizon_minutes,
153131
)
154132

155133
@declared_attr

nowcasting_datamodel/save/update.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,8 @@ def change_forecast_value_to_forecast_last_7_days(
291291

292292
forecast_new = ForecastValueSevenDaysSQL()
293293
for key in ForecastValueSQL.__table__.columns.keys():
294-
if hasattr(forecast, key):
294+
# Dont copy horizon minutes column as this is a generated column
295+
if hasattr(forecast, key) and key != "horizon_minutes":
295296
setattr(forecast_new, key, getattr(forecast, key))
296297

297298
return forecast_new

0 commit comments

Comments
 (0)