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

Option to use alias for model.dict() #205

gmetzker opened this issue Jun 20, 2018 · 1 comment

Option to use alias for model.dict() #205

gmetzker opened this issue Jun 20, 2018 · 1 comment


Copy link

@gmetzker gmetzker commented Jun 20, 2018

I am using pydantic as a very simple serializer of nested model classes. In the models I want to use traditional python snake case for attribute names, but when I dump a dictionary and serialize I want to use camelCase. The alias options seem to be working for parsing an object but when I call .dict() the keys it's using are the standard attribute keys names not the alias.

Would it be possible to introduce an option that would use the alias names when .dict() is called?

Something like this allow_alias_dict_keys:

    def dict(self, *, include: Set[str] = None, exclude: Set[str] = set()) -> Dict[str, Any]:
        Get a dict of the values processed by the model, optionally
        specifying which fields to include or exclude.

        The key/property names will use the alias if there is one.
        if self.Config.allow_alias_dict_keys:
            return {
                self.fields[k].alias: v for k, v in self
                if k not in exclude and (not include or k in include)
            return super().dict(include, exclude)

A general camelCase option would actually be nice as well but not I'm not sure if pydantic was intended for serialization. In any case I really like the package works with the typing library it just seems really easy to use and simple to understand compared to other libraries.

Copy link

@samuelcolvin samuelcolvin commented Jun 20, 2018

Thanks, pleased pydantic is helpful.

I think this was discussed on #160, it would also be useful on #133 I suspect.

I would say probably better to add a kwarg to dict(by_alias=False). Happy to accept a PR for this.

the camelCase option is more complex and involves preferences like "camelCase" vs "CamelCase". However it's should be possible by overriding get_field_config on the Config class. There's some tickery implemented which means when Models inherit from one another, Config will inherit too, so you should be able to implement your own MyBaseModel which overrides Config.get_field_config to apply camel case and use there everywhere.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants