Dismiss type check during create_map
Opened this issue · 4 comments
Hello!
I've been looking for a library like this one and I think it can be pretty useful. I want to use it to convert an object that is mapped from a table of my database (I'm using Tortoise ORM for this):
from tortoise.models import Model
from tortoise import fields
class SessionTable(Model):
__tablename__ = 'sessions'
id = fields.IntField(pk=True)
key = fields.CharField(max_length=8)
to a simple plain object that I use in my use cases (business logic):
@dataclass
class Session:
id:int
key:str
Then, my mapper should be something like:
mapper = ObjectMapper()
mapper.create_map(SessionTable, Session)
mapper.create_map(Session, SessionTable)
...
instance_session = mapper.map(session_table)
instance_sessiontable = mapper.map(session)
But, SessionTable
isn't a type
:
>>> type(SessionTable)
<class 'tortoise.models.ModelMeta'>
so, it fails with ObjectMapperException: type_from must be a type
and ObjectMapperException: type_to must be a type
during the map creation create_map
.
Does it make sense to add a flag to avoid those asserts?
def create_map(self, type_from, type_to, mapping=None, allow_from_any = False, allow_to_any = False):
...
if allow_from_any or (type(type_from) is not type):
...
if allow_to_any or (type(type_to) is not type):
...
Although, I'm not sure if that would work since all data members need a default value. BTW, is it possible to solve that issue? If it is, I'd like to give it a try.
I double this, faced same issue with pydantic and sqlalchemy. Is there are a change for this to be fixed?
Yes Please! Same here
I faced this issue, solved using 1.0.7 version
i changed the lines from:
if type(type_from) is not type:
raise ObjectMapperException("type_from must be a type")
if type(type_to) is not type:
raise ObjectMapperException("type_to must be a type")
to:
if (not isinstance(type_from, type)):
raise ObjectMapperException("type_from must be a type")
if (not isinstance(type_to, type)):
raise ObjectMapperException("type_to must be a type")
this worked well for me.