Skip optional fields
See original GitHub issueFeature Request
We often drop pydantic objects into a NoSQL database where the individual object (document) structure is fairly sparse with quite a few defaults. To save space we often prune out the defaults as they can be regenerated on the fly fairly quickly. To this end, it would be useful to be able to drop results that have been defaulted when serializing automatically.
from pydantic import BaseModel
from typing import Optional
class User(BaseModel):
id: int
value: Optional[int]= None # Or some other decorator like Skip[int]?
u = User(id=5)
>>> print(u)
User id=5 value=None
>>> print(u.dict())
{'id': 5, 'value': None}
# Desired feature
>>> print(u.dict(skip_optional=True))
{'id': 5}
>>> u2 = User(id=5, value=5)
{'id': 5, 'value': 5}
Again, happy to add some code here if this is a feature you would consider.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:8
- Comments:11 (10 by maintainers)
Top Results From Across the Web
Skip optional fields · Issue #378 · pydantic/pydantic - GitHub
when serialising the model, check whether each field's value matches its default, and ignore ones that do. keep a record of which values...
Read more >How to skip Optional.empty fields during Jackson serialization?
I am hoping to get the serializer to skip the field if the Optional is empty, and serialize the contained string if it...
Read more >Optional fields - Vest
Learn how to specify optional fields. ... to tell Vest to conditionally omit the results for this field by providing optional with a...
Read more >Populate Signature field with value from API and Hide "skip ...
Only if the document contains optional field signers will get ''Skip optional fields'' and we will soon be enhancing this option based on...
Read more >Handling optional fields — Chimney 0.6.2 documentation
By default, Chimney does the former (clears the value), but it also gives a simple way to always ignore None from patch with...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Yes
On Fri, 8 Feb 2019, 19:59 Daniel Smith <notifications@github.com wrote:
Incidentally, you can achieve something similar by using a root validator with pre=True to add data for a derived field. So you don’t have a property, but you have the computed value created when the model is created. This works fine for immutable models (which is my use case).