映射SqlAlchemy模型类时出现Unhashable Type错误

报错代码:
@dataclass()
class Order:
    """
    订单收益
    """
    id: str  # 订单标识 = order_id
    customer_id: int  # 消费者标识
    store_id: int  # 店铺标识
    price_currency: str  # 价钱单位
    commodity_price: Decimal  # 商品总价
    commodity_weight: Decimal  # 重量
    shipping_fee: Decimal  # 邮费
    tax_fee: Decimal  # 税费
    total_price: Decimal  # 总金额
    status: OrderIncomeStatus  # 订单收益状态
    payment: Optional[OrderPayment] = field(init=False, default_factory=lambda: None)  # 支付网关
	......

@dataclass()
class OrderPayment:
    """
    支付网关
    """
    id: str  # 支付单号
    gateway: str  # 支付网关: adapay chinapnr stripe
    channel: str  # 支付渠道 微信公众号, 微信小程序, 支付宝
    pipeline_id: str  # 支付商家通道
    paid_time: int  # 支付时间

    def __composite_values__(self):
        return self.id, self.gateway, self.channel, self.pipeline_id, self.paid_time

    def __eq__(self, other):
        return isinstance(other, OrderPayment) and \
               other.id == self.id and \
               other.gateway == self.gateway and \
               other.channel == self.channel and \
               other.pipeline_id == self.pipeline_id and \
               other.paid_time == self.paid_time

    def __ne__(self, other):
        return not self.__eq__(other)

orders_mapper = mapper(Order, orders, properties={
    "payment": composite(OrderPayment, orders.c.payment_id, orders.c.payment_gateway, orders.c.payment_channel,orders.c.payment_pipeline_id, orders.c.paid_time),
})
报错:
unhashable type: 'OrderPayment'
错误原因:

当构建orm的时候,sqlalchemy会调用到子类的hash结果,但OrderPayment类中并没有hash的返回,所以会报这个错误

解决:

为OrderPayment加上__hash__方法:

@dataclass()
class OrderPayment:
    """
    支付网关
    """
    id: str  # 支付单号
    gateway: str  # 支付网关: adapay chinapnr stripe
    channel: str  # 支付渠道 微信公众号, 微信小程序, 支付宝
    pipeline_id: str  # 支付商家通道
    paid_time: int  # 支付时间

    def __composite_values__(self):
        return self.id, self.gateway, self.channel, self.pipeline_id, self.paid_time

    def __eq__(self, other):
        return isinstance(other, OrderPayment) and \
               other.id == self.id and \
               other.gateway == self.gateway and \
               other.channel == self.channel and \
               other.pipeline_id == self.pipeline_id and \
               other.paid_time == self.paid_time

    def __ne__(self, other):
        return not self.__eq__(other)
        
    def __hash__(self):
        return hash(f"{self.__class__.__module__}.{self.__class__.__name__}.{self.id}")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: SQLAlchemy 是一个 Python SQL 框架。它提供了一组用于与数据库交互的高级对象关系映射(ORM)工具。在 SQLAlchemy 中,模型是用来表示数据库中的表的 Python 类。模型类中的字段映射到数据库表中的列。备注可以通过在模型类中定义 docstring 来实现。 ### 回答2: 在 SQLAlchemy 模型中,备注是用来描述数据库表的各个字段的属性、含义和限制条件的文本。备注对于理解和维护数据库结构非常重要,可以提供更清晰的数据模型定义和文档化。 在 SQLAlchemy 中,我们可以使用 `Column` 对象的 `doc` 参数来添加字段的备注。例如: ``` from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(50), nullable=False, doc='用户的用户名') password = Column(String(50), nullable=False, doc='用户的密码') ``` 上面的代码中,我们在 `Column` 对象的构造函数中使用了 `doc` 参数,通过这个参数可以添加字段的备注。在这个例子中,我们为 `username` 和 `password` 字段添加了对应的备注。 备注可以是任何字符串,用来描述字段的特点、功能、限制条件等。在开发过程中,可以使用备注来记录字段的约束、验证规则,或者提供字段的用法示例。 当我们使用 SQLAlchemy 创建数据库表时,可以在模型定义结束后,使用 `create_all()` 方法来生成表结构。在生成表结构时,SQLAlchemy 会自动获取字段的备注,并将其存储在数据库元数据中,从而实现数据库表字段的文档化。 总之,使用 SQLAlchemy模型备注可以提供更清晰、更方便的数据库模型定义和文档化方式,方便开发人员理解、维护和使用数据库。 ### 回答3: SQLAlchemy 模型备注指的是对 SQLAlchemy 模型定义中的字段或表格进行注释或描述的功能。通常用于提供关于模型的额外信息,方便开发者阅读和理解模型的结构和用途。 在 SQLAlchemy 中,可以使用 `__doc__` 属性来为模型添加注释。例如,假设我们有一个名为 `User` 的模型,我们可以通过在模型类的定义中添加注释来描述该模型的作用: ```python class User(db.Model): """ 用户模型 """ __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(50)) email = db.Column(db.String(120)) def __repr__(self): return '<User %r>' % self.username ``` 在上面的例子中,我们使用了 `"""` 符号来添加多行注释,对这个模型进行了简短的描述。开发者可以通过查看这个注释来快速了解这个模型的作用和属性。 使用模型备注的好处有: 1. 提供了模型的说明和描述,有助于团队成员更好地理解并使用模型; 2. 对于复杂的模型,可以明确每个字段和关系的作用,减少开发者的困惑; 3. 在文档生成工具使用时,模型备注可以作为文档的一部分,方便查阅和参考。 总之,SQLAlchemy 模型备注是一种用于注释和描述模型的功能,可以提供额外的信息,方便开发者使用和理解模型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值