Situation
Users make purchases, which are stored as transactions in 3 different tables (depending on the type). I need to calculate total amount of transactions/purchases of female and male users, so I need to look into all 3 tables.
For this I created a @property in the User table:
@property
def count_credits_purchases(self):
trans = object_session(self).query(Transaction_1).filter(Transaction_1.type == "credits").with_parent(self).count()
trans_vk = object_session(self).query(Transaction_2).filter(Transaction_2.type == "credits").with_parent(self).count()
trans_stripe = object_session(self).query(Transaction_3).filter(Transaction_3.type == "credits").with_parent(self).count()
value = trans + trans_vk + trans_stripe
return int(value)
I am trying to calculate the total amount of purchases by using sqlalchemy func.sum():
total_purchases_males_credits = db_session.query(func.sum(Users.count_credits_purchases))
.filter(Users.date_added >= start_date, Users.date_added <= end_date, Users.gender == "1")
.scalar()
Problem
AttributeError: 'property' object has no attribute 'translate'
The translate method is a string method, what is happening here? I definitely return an integer in count_credits_purchases.
I made a test and checking the value per user is always correct:
all_users = db_session.query(Users).limit(200)
for user in all_users:
print (user.count_credits_purchases) # gives correct result
I could make a variable and calculate it in the loop, but it is super unefficient and would need probably 1 hour if there are 50k users. I need to understand how to work with the @property attribute
hybrid_property?