def getBeforePoint(userId):
today = datetime.now()
subquery = (
db.session.query(
T_user_point.acquired_at,
M_promotion_code.valid_days,
T_user_promotion_code.promotion_code_id,
T_user_point.user_promotion_code_id,
T_user_promotion_code.user_promotion_code_id,
)
.join(T_user_promotion_code, T_user_point.user_promotion_code_id == T_user_promotion_code.user_promotion_code_id)
.join(M_promotion_code, T_user_promotion_code.promotion_code_id == M_promotion_code.promotion_code_id)
.filter(T_user_point.user_id == userId)
.subquery()
)
result = db.session.query(
subquery.c.acquired_at,
subquery.c.valid_days
).all()
loop_counter = 0
point_with_valid_days = 0
for row in result:
acquired_at = row.acquired_at
valid_days = row.valid_days
if valid_days is not None:
valid_duration = timedelta(days=valid_days)
expiration_date = acquired_at + timedelta(days=valid_days)
point_expiration_date = func.cast(acquired_at + timedelta(days=valid_days), DATE)
if today < expiration_date:
point_with_valid_days = (
db.session.query(func.sum(T_user_point.point))
.join(subquery, T_user_point.user_promotion_code_id == subquery.c.user_promotion_code_id)
.filter(
T_user_point.user_id == userId,
T_user_point.is_deleted == False,
subquery.c.valid_days.isnot(None),
today < point_expiration_date,
T_user_point.user_promotion_code_id == T_user_promotion_code.user_promotion_code_id
)
.scalar() or 0
)
else:
point_with_valid_days += 0
loop_counter += 1
print('point_with_valid_days', point_with_valid_days)
In the database, there are 50 expired points (today < point_expiration_date is False) and 10 points that have not yet expired (today < point_expiration_date is True).
In the code above, I expected print(‘point_with_valid_days’, point_with_valid_days) to print 10, but it actually prints 60.
I don’t know where I’m going wrong.
If someone can help me find the mistake in my code, it would be helpful.
I tried to check the loop. It loops twice, so I don’t think there’s a problem with the loop.