Skip to content

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

@gmetzker

Description

@gmetzker

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)
            }
        else:
            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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions