如何解决有没有办法根据多行的结果处理自定义类型? 类似于复合材料
有一个表格,其中第一列的类型取决于第二列。
Object
type: str # controll field
option: str # dependent filed
我使用的是sqlalchemy和@dataclass,所以代码应该是:
from typing import Union
from dataclasses import dataclass,field
from sqlalchemy.orm import registry
from sqlalchemy.types import Unicode,UnicodeText
from sqlalchemy import Column,Table
mapper_registry = registry()
@dataclass
class Option1:
a: int = 1
@dataclass
class Option2:
b: int = 1
class OptionType(TypeDecorator):
impl = UnicodeText
def load_dialect_impl(self,dialect):
return UnicodeText()
def process_bind_param(self,value,dialect):
# I need to transform value in this place to DB - easier part,# because is possible to check a type of the value
# self.type does not exist
if self.type == "a":
return value.a
return value.b
def process_result_value(self,dialect):
# I need to transform object from database
# information depends on value from :type: field
# self.type does not exist
if self.type == "a":
return Option1(a=value)
return Option2(b=value)
table = Table(
"object",mapper_registry.metadata,Column("type",Unicode(50),primary_key=True,nullable=False),Column("option",OptionType),)
@mapper_registry.mapped
@dataclass
class Object:
__table__ = table
type: str = "Option1"
options: Union[Option1,Option2] = field(default_factory=Option1)
我已经检查了 composite type,但有一个问题,因为这不是复合,而是对象转换。
我已经检查了来自 dataclasses 的 __post_init__
调用,但是这个方法不是用 sqlalchemy 的组合调用的。
在我看来,如何转换选项列的值的最好方法是了解其他字段的上下文,但我明白为什么会受到限制。
你知道如何在不检查列选项的情况下解决这个问题吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。