报错代码:
@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}")