When creating a Pydantic model you can create an instance of it without Optional arguments, and when exporting as a dictionary you can pass 'exclude_unset' to exclude optional fields from the return dict. https://pydantic-docs.helpmanual.io/usage/exporting_models/
In [1]: from pydantic import BaseModel
In [2]: from typing import Optional
class User(BaseModel):
id: int
name: str
surname: Optional[str]
In [3]: user = User(id=1, name="Test")
In [4]: user.dict(exclude_unset=True)
Out[4]: {'id': 1, 'name': 'Test'}
After creating a strawberry.experimental.pydantic.type which uses a pydantic model, you should be able to convert an instance of that type to_pydantic and export a dict the same way with 'exclude_unset' and return all fields that haven't been set but it returns all fields instead.
Example:
import strawberry
from typing import Optional
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
surname: Optional[str]
@strawberry.experimental.pydantic.type(model=User, all_fields=True)
class UserType:
pass
In [2]: user = UserType(id=1, name="Test")
Actual output:
In [3]: user.to_pydantic().dict(exclude_unset=True)
Out[3]: {'id': 1, 'name': 'Test', 'surname': None}
Expected output:
In [3]: user.to_pydantic().dict(exclude_unset=True)
Out[3]: {'id': 1, 'name': 'Test'}
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too