TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute
Problem Description:
i am also getting error while doing this task.
Models.py
CloudImageMaster
created_tmstmp = Column(DateTime(), default = datetime.now(timezone.utc))
ClientMaster
ttl = Column(BigInteger, nullable=False)
QUERY:-
db.query(CloudImageMaster).join(ClientMaster).filter(
(
CloudImageMaster.created_tmstmp + timedelta(microseconds=ClientMaster.ttl)
) < today
).all()
ERROR MESSAGE :-
TypeError: unsupported type for timedelta microseconds component: InstrumentedAttribute
I tried above. It should work as per the code. What i am doing wrong in this.
Solution – 1
Given a filter expression like MyMode.attr == something
, the left hand side (LHS) can be thought of as belonging to the database side, the right hand side (RHS) as belonging to the application. What this means is that the RHS must be expressed in what SQLAlchemy regards as database constructs (ORM entities, tables, columns, database functions) while the LHS is expressed as normal Python code.
This means that we can’t subtract a timedelta
(a Python construct) from a Datetime
column (a database construct); we have to convert the timedelta
to a database construct – a PostgreSQL interval. We can do this by using the make_interval function, dividing ttl
by 1000 as make_interval
does not accept a microsecond argument.
from sqlalchemy import func
db.query(CloudImageMaster)
.join(ClientMaster)
.filter(
(
CloudImageMaster.created_tmstmp
+ func.make_interval(0, 0, 0, 0, 0, 0, ClientMaster.ttl /1000)
) < today
).all()