Reputation: 31
Is there any way in SQLAlchemy to perform some kind of 'deep mapping' of the class attributes?
For instance: obj.attr.nested_attr
, I'd like to tell obj
mapper how to directly map nested_attr
to a nested_attr
column in a table.
Python: 3.10.7
SQLAlchemy: 1.4.41
Let's say we have domain model of:
@dataclass
class FullName:
first_name: str
last_name: str
@dataclass
class User:
name: FullName
date_of_birth: datetime
etc...
And an SQLAlchemy table model like:
users = sqlalchemy.Table(
"users",
metadata,
sqlalchemy.Column("first_name", sqlalchemy.String),
sqlalchemy.Column("last_name", sqlalchemy.String),
etc...
)
Is there any way in SQLAlchemy to map name
(which is of type FullName
) attributes first_name
and last_name
to users
table columns first_name
and last_name
?
I tried:
mapper_registry = registry()
mapper_registry.map_imperatively(
User,
users,
properties={
"name.first_name": users.c.first_name,
"name.last_name": users.c.last_name,
},
)
However, SQLAlchemy doesn't seem to comprehend accessing attributes' of an attribute by dot notation.
Is there any other way to directly map user.name.first_name
to first_name
column of the users
table?
Upvotes: 3
Views: 293