Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support of a custom mapping to the fields with different names #225

Open
scrobot opened this issue Mar 11, 2023 · 1 comment
Open

Support of a custom mapping to the fields with different names #225

scrobot opened this issue Mar 11, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@scrobot
Copy link

scrobot commented Mar 11, 2023

I have one common problem. My model/entity has a field that might be related to the DTO but with different naming and type.

@dataclass
class User:
    secret: str
    name: str
    created_at: datetime = datetime.now()
    updated_at: datetime = datetime.now()
    _id: ObjectId = ObjectId()

@dataclass
class UserResponse(BaseModel):
    id: str
    name: str
    created_at: datetime
    updated_at: datetime

I'm of opinion that the best way to resolve this problem would be to add some customization to the mapping

    def find_user(self, user_id) -> UserResponse:
        data = self.user_repository.get_user_by_id(user_id)
        return from_dict(
            UserResponse,
            data,
            config=Config(
                cast=[ObjectId, datetime],
                mapping={
                    id: lambda value: str(value._id)
                }
            )
        )

Or maybe apply some "magic" :) but I'm not pretty sure) Just for the thinking about.

@dataclass
@map({'id': '_id'})
class UserResponse(BaseModel): 
    id: str
    name: str
    created_at: datetime
    updated_at: datetime
@scrobot scrobot added the enhancement New feature or request label Mar 11, 2023
@scrobot scrobot changed the title Support of a custom mapping in the field with different names Support of a custom mapping in the fields with different names Mar 11, 2023
@scrobot scrobot changed the title Support of a custom mapping in the fields with different names Support of a custom mapping to the fields with different names Mar 11, 2023
@jmhodges-color
Copy link

Just run into this with REST API dictionaries that include a self key (that's the canonical URL back for the object) which is unusable as a field name in dataclasses and get you errors like:

SyntaxError: duplicate argument 'self' in function definition

An alternative to the decorator implementation would be to use field(metadata=...), but either could work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants