gpt4 book ai didi

python - SQLAlchemy 属性错误 : 'property' object has no attribute 'translate'

转载 作者:行者123 更新时间:2023-11-29 05:53:40 24 4
gpt4 key购买 nike

情况

用户进行购买,这些购买作为交易存储在 3 个不同的表中(取决于类型)。我需要计算女性和男性用户的交易/购买总额,因此我需要查看所有 3 个表。

为此,我在用户表中创建了一个@property:

@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)

我正在尝试使用 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()

问题

AttributeError: 'property' object has no attribute 'translate'

translate 方法是一个字符串方法,这里发生了什么?我肯定会在 count_credits_purchases 中返回一个整数。

我做了一个测试,检查每个用户的值总是正确的:

all_users = db_session.query(Users).limit(200)
for user in all_users:
print (user.count_credits_purchases) # gives correct result

我可以创建一个变量并在循环中计算它,但它非常低效,如果有 50k 用户,可能需要 1 小时。我需要了解如何使用 @property 属性

最佳答案

作为文档 Using Descriptors and Hybrids说你应该使用 hybrid_property以便能够在您的查询中使用它们。

看看文档中的示例:

class EmailAddress(Base):
__tablename__ = 'email_address'

id = Column(Integer, primary_key=True)

# name the attribute with an underscore,
# different from the column name
_email = Column("email", String)

# then create an ".email" attribute
# to get/set "._email"
@property
def email(self):
return self._email

While our EmailAddress object will shuttle the value through the email descriptor and into the _email mapped attribute, the class level EmailAddress.email attribute does not have the usual expression semantics usable with Query. To provide these, we instead use the hybrid extension

关于python - SQLAlchemy 属性错误 : 'property' object has no attribute 'translate' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51782913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com