Skip to content

Conversation

PrettyWood
Copy link
Collaborator

@PrettyWood PrettyWood commented Apr 10, 2021

Change Summary

Allow to customize serialization of fields with BaseModel type

from typing import List, Optional

from pydantic import BaseModel


class Address(BaseModel):
    city: str
    country: str


class User(BaseModel):
    name: str
    address: Address
    friends: Optional[List['User']] = None

    class Config:
        json_encoders = {
            Address: lambda a: f'{a.city} ({a.country})',
            'User': lambda u: f'{u.name} in {u.address.city} '
                              f'({u.address.country[:2].upper()})',
        }


User.update_forward_refs()

wolfgang = User(
    name='Wolfgang',
    address=Address(city='Berlin', country='Deutschland'),
    friends=[
        User(name='Pierre', address=Address(city='Paris', country='France')),
        User(name='John', address=Address(city='London', country='UK')),
    ],
)
print(wolfgang.json())
# {"name": "Wolfgang", "address": "Berlin (Deutschland)", "friends": ["Pierre in Paris (FR)", "John in London (UK)"]}

Related issue number

#2622

Checklist

  • Unit tests for the changes exist
  • Tests pass on CI and coverage remains at 100%
  • Documentation reflects the changes where applicable
  • changes/<pull request or issue id>-<github username>.md file added describing change
    (see changes/README.md for details)

@PrettyWood PrettyWood force-pushed the nested-models-serialize branch from 00be9f8 to 00f38c4 Compare April 10, 2021 22:22
@PrettyWood PrettyWood changed the title feat: allow JSON serialization of nested models feat: make JSON serialization of referenced pydantic models possible Apr 10, 2021
Copy link
Member

@samuelcolvin samuelcolvin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like a good start.

@samuelcolvin
Copy link
Member

please update.

@github-actions github-actions bot added awaiting author revision awaiting changes from the PR author and removed ready for review labels May 9, 2021
@PrettyWood
Copy link
Collaborator Author

Thanks for the remarks. Please review the updated version

@github-actions github-actions bot added ready for review and removed awaiting author revision awaiting changes from the PR author labels May 12, 2021
@mcauto
Copy link

mcauto commented Dec 1, 2021

When is it merging?

@samuelcolvin samuelcolvin merged commit 458f257 into pydantic:master Dec 7, 2021
@samuelcolvin
Copy link
Member

thank you.

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

Successfully merging this pull request may close these issues.

3 participants