49

I'm making an API with FastAPI and Pydantic.

I would like to have some PATCH endpoints, where 1 or N fields of a record could be edited at once. Moreover, I would like the client to only pass the necessary fields in the payload.

Example:

class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float


@app.post("/items", response_model=Item)
async def post_item(item: Item):
    ...

@app.patch("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
    ...

In this example, for the POST request, I want every field to be required. However, in the PATCH endpoint, I don't mind if the payload only contains, for example, the description field. That's why I wish to have all fields as optional.

Naive approach:

class UpdateItem(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    price: Optional[float] = None
    tax: Optional[float]

But that would be terrible in terms of code repetition.

Any better option?

Chris
  • 18,724
  • 6
  • 46
  • 80
nolwww
  • 1,355
  • 1
  • 15
  • 33

11 Answers11

44

This method prevents data validation

Read this by @Anime Bk: https://stackoverflow.com/a/75011200

Solution with metaclasses

I've just come up with the following:


class AllOptional(pydantic.main.ModelMetaclass):
    def __new__(cls, name, bases, namespaces, **kwargs):
        annotations = namespaces.get('__annotations__', {})
        for base in bases:
            annotations.update(base.__annotations__)
        for field in annotations:
            if not field.startswith('__'):
                annotations[field] = Optional[annotations[field]]
        namespaces['__annotations__'] = annotations
        return super().__new__(cls, name, bases, namespaces, **kwargs)

Use it as:

class UpdatedItem(Item, metaclass=AllOptional):
    pass

So basically it replace all non optional fields with Optional

Any edits are welcome!

With your example:

from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel
import pydantic

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float


class AllOptional(pydantic.main.ModelMetaclass):
    def __new__(self, name, bases, namespaces, **kwargs):
        annotations = namespaces.get('__annotations__', {})
        for base in bases:
            annotations.update(base.__annotations__)
        for field in annotations:
            if not field.startswith('__'):
                annotations[field] = Optional[annotations[field]]
        namespaces['__annotations__'] = annotations
        return super().__new__(self, name, bases, namespaces, **kwargs)

class UpdatedItem(Item, metaclass=AllOptional):
    pass

# This continues to work correctly
@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
    return {
        'name': 'Uzbek Palov',
        'description': 'Palov is my traditional meal',
        'price': 15.0,
        'tax': 0.5,
    }

@app.patch("/items/{item_id}") # does using response_model=UpdatedItem makes mypy sad? idk, i did not check
async def update_item(item_id: str, item: UpdatedItem):
    return item
Drdilyor
  • 1,250
  • 1
  • 12
  • 30
  • 1
    Hey - the solution doesn't appear to work for nested models, as in, if I have a model as an attribute of another and apply the metaclass to both of these objects, parse_obj will through validation errors. Any thoughts? – hi im Bacon Jun 15 '22 at 15:04
  • 1
    @hiimBacon does Maxim's solution work for that case? – Drdilyor Jun 18 '22 at 08:37
14

Modified @Drdilyor's solution

Added checking for nesting of models.

from pydantic.main import ModelMetaclass, BaseModel
from typing import Any, Dict, Optional, Tuple

class _AllOptionalMeta(ModelMetaclass):
    def __new__(self, name: str, bases: Tuple[type], namespaces: Dict[str, Any], **kwargs):
        annotations: dict = namespaces.get('__annotations__', {})

        for base in bases:
            for base_ in base.__mro__:
                if base_ is BaseModel:
                    break

                annotations.update(base_.__annotations__)

        for field in annotations:
            if not field.startswith('__'):
                annotations[field] = Optional[annotations[field]]

        namespaces['__annotations__'] = annotations

        return super().__new__(mcs, name, bases, namespaces, **kwargs)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Maxim
  • 141
  • 2
  • 3
11

The problem is once FastAPI sees item: Item in your route definition, it will try to initialize an Item type from the request body, and you can't declare your model's fields to be optional sometimes depending on some conditional, such as depending on which route it is used.

I have 3 solutions:

Solution #1: Separate Models

I would say that having separate models for the POST and PATCH payloads seems to be the more logical and readable approach. It might lead to duplicated code, yes, but I think clearly defining which route has an all-required or an all-optional model balances out the maintainability cost.

The FastAPI docs has a section for partially updating models with PUT or PATCH that uses Optional fields, and there's a note at the end that says something similar:

Notice that the input model is still validated.

So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or None).

So...

class NewItem(BaseModel):
    name: str
    description: str
    price: float
    tax: float

class UpdateItem(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    price: Optional[float] = None
    tax: Optional[float] = None

@app.post('/items', response_model=NewItem)
async def post_item(item: NewItem):
    return item

@app.patch('/items/{item_id}',
           response_model=UpdateItem,
           response_model_exclude_none=True)
async def update_item(item_id: str, item: UpdateItem):
    return item

Solution #2: Declare as All-Required, but Manually Validate for PATCH

You can define your model to have all-required fields, then define your payload as a regular Body parameter on the PATCH route, and then initialize the actual Item object "manually" depending on what's available in the payload.

from fastapi import Body
from typing import Dict

class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float

@app.post('/items', response_model=Item)
async def post_item(item: Item):
    return item

@app.patch('/items/{item_id}', response_model=Item)
async def update_item(item_id: str, payload: Dict = Body(...)):
    item = Item(
        name=payload.get('name', ''),
        description=payload.get('description', ''),
        price=payload.get('price', 0.0),
        tax=payload.get('tax', 0.0),
    )
    return item

Here, the Item object is initialized with whatever is in the payload, or some default if there isn't one. You'll have to manually validate if none of the expected fields are passed, ex.:

from fastapi import HTTPException

@app.patch('/items/{item_id}', response_model=Item)
async def update_item(item_id: str, payload: Dict = Body(...)):
    # Get intersection of keys/fields
    # Must have at least 1 common
    if not (set(payload.keys()) & set(Item.__fields__)):
        raise HTTPException(status_code=400, detail='No common fields')
    ...
$ cat test2.json
{
    "asda": "1923"
}
$ curl -i -H'Content-Type: application/json' --data @test2.json --request PATCH localhost:8000/items/1
HTTP/1.1 400 Bad Request
content-type: application/json

{"detail":"No common fields"}

The behavior for the POST route is as expected: all the fields must be passed.

Solution #3: Declare as All-Optional But Manually Validate for POST

Pydantic's BaseModel's dict method has exclude_defaults and exclude_none options for:

  • exclude_defaults: whether fields which are equal to their default values (whether set or otherwise) should be excluded from the returned dictionary; default False

  • exclude_none: whether fields which are equal to None should be excluded from the returned dictionary; default False

This means, for both POST and PATCH routes, you can use the same Item model, but now with all Optional[T] = None fields. The same item: Item parameter can also be used.

class Item(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    price: Optional[float] = None
    tax: Optional[float] = None

On the POST route, if not all the fields were set, then exclude_defaults and exclude_none will return an incomplete dict, so you can raise an error. Else, you can use the item as your new Item.

@app.post('/items', response_model=Item)
async def post_item(item: Item):
    new_item_values = item.dict(exclude_defaults=True, exclude_none=True)

    # Check if exactly same set of keys/fields
    if set(new_item_values.keys()) != set(Item.__fields__):
        raise HTTPException(status_code=400, detail='Missing some fields..')

    # Use `item` or `new_item_values`
    return item
$ cat test_empty.json
{
}
$ curl -i -H'Content-Type: application/json' --data @test_empty.json --request POST localhost:8000/items
HTTP/1.1 400 Bad Request
content-type: application/json

{"detail":"Missing some fields.."}

$ cat test_incomplete.json 
{
    "name": "test-name",
    "tax": 0.44
}
$ curl -i -H'Content-Type: application/json' --data @test_incomplete.json --request POST localhost:8000/items
HTTP/1.1 400 Bad Request
content-type: application/json

{"detail":"Missing some fields.."}

$ cat test_ok.json
{
    "name": "test-name",
    "description": "test-description",
    "price": 123.456,
    "tax": 0.44
}
$ curl -i -H'Content-Type: application/json' --data @test_ok.json --request POST localhost:8000/items
HTTP/1.1 200 OK
content-type: application/json

{"name":"test-name","description":"test-description","price":123.456,"tax":0.44}

On the PATCH route, if at least 1 value is not default/None, then that will be your update data. Use the same validation from Solution 2 to fail if none of the expected fields were passed in.

@app.patch('/items/{item_id}', response_model=Item)
async def update_item(item_id: str, item: Item):
    update_item_values = item.dict(exclude_defaults=True, exclude_none=True)

    # Get intersection of keys/fields
    # Must have at least 1 common
    if not (set(update_item_values.keys()) & set(Item.__fields__)):
        raise HTTPException(status_code=400, detail='No common fields')

    update_item = Item(**update_item_values)

    return update_item
$ cat test2.json
{
    "asda": "1923"
}
$ curl -i -s -H'Content-Type: application/json' --data @test2.json --request PATCH localhost:8000/items/1
HTTP/1.1 400 Bad Request
content-type: application/json

{"detail":"No common fields"}

$ cat test2.json
{
    "description": "test-description"
}
$ curl -i -s -H'Content-Type: application/json' --data @test2.json --request PATCH localhost:8000/items/1
HTTP/1.1 200 OK
content-type: application/json

{"name":null,"description":"test-description","price":null,"tax":null}
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • Thanks ! Great explanations. So, it looks like solution 2 is better than 3 as the manual validation for PATCH has to be done in both, while POST validation only in 3. But I agree solution 1 is easier to read when you are not alone in a project ... – nolwww May 26 '21 at 18:44
  • Ah Pydantic, where instead of one model, we now need at least 3. – Callam Delaney Apr 17 '23 at 21:39
8

Using a decorator

Using separate models seems like a bad idea for large projects. Lots of effectively duplicated code making it much harder to maintain. The goal of this is reusability and flexibility

from typing import Optional, get_type_hints, Type

from pydantic import BaseModel


def make_optional(
    include: Optional[list[str]] = None,
    exclude: Optional[list[str]] = None,
):
    """Return a decorator to make model fields optional"""

    if exclude is None:
        exclude = []

    # Create the decorator
    def decorator(cls: Type[BaseModel]):
        type_hints = get_type_hints(cls)
        fields = cls.__fields__
        if include is None:
            fields = fields.items()
        else:
            # Create iterator for specified fields
            fields = ((name, fields[name]) for name in include if name in fields)
            # Fields in 'include' that are not in the model are simply ignored, as in BaseModel.dict
        for name, field in fields:
            if name in exclude:
                continue
            if not field.required:
                continue
            # Update pydantic ModelField to not required
            field.required = False
            # Update/append annotation
            cls.__annotations__[name] = Optional[type_hints[name]]
        return cls

    return decorator

Usage

In the context of fast-api models

class ModelBase(pydantic.BaseModel):
  a: int
  b: str


class ModelCreate(ModelBase):
  pass

# Make all fields optional
@make_optional()
class ModelUpdate(ModelBase):
  pass
  • By default, all fields are made optional.
  • include specifies which fields to make optional; all other fields remain unchanged.
  • exclude specifies which fields not to affect.
  • exclude takes precedence over include.
# Make only `a` optional
@make_optional(include=["a"])
class ModelUpdate(ModelBase):
  pass

# Make only `b` optional
@make_optional(exclude=["a"])
class ModelUpdate(ModelBase):
  pass

Note: pydantic appears to make copies of the fields when you inherit from a base class, which is why it's ok to change them in-place

mishnea
  • 111
  • 1
  • 4
  • This is a nice clean alternative and a creative idea to use a decorator. I wonder if you could help with 2 improvements: 1. clarify use of `include` and `exclude` parameters to the decorator, as it's not clear to me which "way round" the sense / meaning is of those. Perhaps illustrate with a usage example. 2. please fix up to apply to nested models (in my case I only have two sub-objects, so only one extra level) – NeilG Jan 18 '23 at 11:05
  • 1
    @NeilG Thanks for the feedback. I've added clarification about the `include` & `exclude` fields. I need to spend a little more time to think about the nested models which I can't right now. It's not ideal, but you could try something like this: ```python class A(BaseModel): ... class B(BaseModel): a: A ... @make_optional() class OptB(B): a: make_optional()(A) ... ``` This is not so bad for just one level but yeah, it would be worth adding support for nested models. – mishnea Jan 19 '23 at 14:11
  • 1
    @NeilG sorry about the formatting, it will only let me edit every 5 mins and I didn't know you can't add code blocks to comments – mishnea Jan 19 '23 at 14:17
  • Thanks @mishnea, this is great, except I don't think it descends into nested classes, does it? – NeilG Jan 20 '23 at 00:00
  • 1
    This solution worked for me, however, you lose the config from the base model class. In my case, I needed to add this back in by adding it to the `create_model` call like this: `create_model(f'{baseclass.__name__}Update', **_fields, __validators__=validators, __config__=baseclass.Config)` – camraynor Jun 20 '23 at 20:45
6

For my case creating a new class was the only solution that worked, but packed into a function it is quite convenient:

from pydantic import BaseModel, create_model
from typing import Optional
from functools import lru_cache

@lru_cache(maxsize=None) # avoids creating many classes with same name
def make_optional(baseclass: Type[BaseModel]) -> Type[BaseModel]:
    # Extracts the fields and validators from the baseclass and make fields optional
    fields = baseclass.__fields__
    validators = {'__validators__': baseclass.__validators__}
    optional_fields = {key: (Optional[item.type_], None)
                       for key, item in fields.items()}
    return create_model(f'{baseclass.__name__}Optional', **optional_fields,
                        __validators__=validators)

class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float

ItemOptional = make_optional(Item)

Comparing after and before:

> Item.__fields__

{'name': ModelField(name='name', type=str, required=True),
 'description': ModelField(name='description', type=str, required=True),
 'price': ModelField(name='price', type=float, required=True),
 'tax': ModelField(name='tax', type=float, required=True)}

> ItemOptional.__fields__

{'name': ModelField(name='name', type=Optional[str], required=False, default=None),
 'description': ModelField(name='description', type=Optional[str], required=False, default=None),
 'price': ModelField(name='price', type=Optional[float], required=False, default=None),
 'tax': ModelField(name='tax', type=Optional[float], required=False, default=None)}

It does work, and also it allows you to filter out some fields in the dict_comprehension if it is required.

Moreover in fastapi this approach allows you to do something like this:

@app.post("/items", response_model=Item)
async def post_item(item: Item = Depends()):
    ...

@app.patch("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: make_optional(Item) = Depends()):
    ...

Which reduces a lot the boilerplate, using the same approach you can also make a function that makes optional the fields and also exclude a field in case your Item has an ID field,the id would will be repeated in your PATCH call. That can be solved like this:

def make_optional_no_id(baseclass):
    ... # same as make optional
    optional_fields = {key: (Optional[item.type_], None) 
                       for key, item in fields.items() if key != 'ID'} # take out here ID
    ... # you can also take out also validators of ID

@app.patch("/items/{item_id}", response_model=Item)
async def update_item(item: make_optional_no_id(Item) = Depends()):
Ziur Olpa
  • 1,839
  • 1
  • 12
  • 27
  • I think I like this one even more than the decorator, because you can just stick it in a dependency and then there's nothing else to distract. This makes a lot of sense. I wonder if you could please update it to support nested models? – NeilG Jan 18 '23 at 11:11
  • 1
    It's being many months since I did this code, but if you provide a snippet supporting that case I will update my answer. In any case if you use this approach several times with the same class I recommend to cache the result to prevent having many classes with the same name. I have edited my answer to prevent that. – Ziur Olpa Jan 18 '23 at 12:33
  • Did you just add the `lru_cache`? I'm not sure if I saw it there before. I guess that deals with that problem very nicely. Thanks for your offer. If it's ok with you I might just create a new question and link it here. I'm not sure where to put the snippet otherwise. – NeilG Jan 18 '23 at 22:19
  • 1
    yes lru_cache is the new edition, and sure, as you want. – Ziur Olpa Jan 18 '23 at 22:32
  • Thanks again for your help and support @Ziur_Olpa. I have posted a new question here: https://stackoverflow.com/q/75167317/134044 – NeilG Jan 19 '23 at 02:52
  • I'm not sure if you started work on the sub-classes yet @Zuir_Olpa, but I've ended up working on it myself. I think I've got a solution but I need to test it and then I'll post it. If you haven't spent any time on it yet you may want to wait until I've posted mine. – NeilG Jan 20 '23 at 06:27
  • @NeilG sure i wait, great to know :) – Ziur Olpa Jan 20 '23 at 08:07
  • Hey @Ziur_Olpa, pretty funny, I got it working, but my test PATCH wasn't working, and still isn't. At first I thought it was implementation of `make_optional` but I've drilled down and found out several things that are wrong with other aspects of the PATCH. So FYI, you shouldn't use `Depends` with it (probably need `Body` or something like that) but also I find that Pydantic's `BaseModel.copy(update=, deep-True)` doesn't respect sub-objects as `BaseModel`. It seems to treat them as `dict`. I could have a Pydantic bug/feature here. Still working on it ... – NeilG Jan 21 '23 at 06:36
  • There is some discussion on a class-based solution to be built into Pydantic, possibly in v2: https://github.com/pydantic/pydantic/discussions/3089 – NeilG Jan 21 '23 at 08:27
  • Yes, this issue is acknowledged in Pydantic and relates to the inability of `BaseModel.copy` to properly treat sub-objects, as described, reflected in these two issues which are closely similar: https://github.com/pydantic/pydantic/issues/4177 and https://github.com/pydantic/pydantic/issues/3785 – NeilG Jan 21 '23 at 09:03
  • Hi @Zuir_Olpa, developing your answer further I've now added support for nested models. I've also got a working solution for `PATCH`ing Pydantic nested `BaseModel` without using `BaseModel.copy`, which fails to update correctly for nested models. So my `PATCH` now works: https://stackoverflow.com/a/75205570 – NeilG Jan 23 '23 at 04:07
4

⛔️ Pay attention, @Drdilyor's solution prevent Fields validation.

It seems that @Drdilyor's solution cancels all the fields validation

Let's say you have :

from typing import Optional
import pydantic
from pydantic import BaseModel, Field

class AllOptional(pydantic.main.ModelMetaclass):
    def __new__(self, name, bases, namespaces, **kwargs):
        annotations = namespaces.get('__annotations__', {})
        for base in bases:
            annotations.update(base.__annotations__)
        for field in annotations:
            if not field.startswith('__'):
                annotations[field] = Optional[annotations[field]]
        namespaces['__annotations__'] = annotations
        return super().__new__(self, name, bases, namespaces, **kwargs)

class A(BaseModel):
    a:int = Field(gt=1)

class AO(A, metaclass=AllOptional):
    pass

AO(a=-1) # This will pass through the validation even that it's wrong ⛔️

A simple alternative

class AllOptional(pydantic.main.ModelMetaclass):
    def __new__(mcls, name, bases, namespaces, **kwargs):
        cls = super().__new__(mcls, name, bases, namespaces, **kwargs)
        for field in cls.__fields__.values():
            field.required=False
        return cls
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Amine Bk
  • 41
  • 2
  • 1
    Thanks for the warning, @Amine_Bk. I haven't tested but if this is correct then I will use Zuir's answer https://stackoverflow.com/a/72365032/134044 because I think it's taking the same approach you are (functionally iterating over already built instance) but doesn't require going down into `__new__` and can just be applied as a dependency with no other distraction in the code. – NeilG Jan 18 '23 at 11:16
  • 1
    Thanks for the catch! I will link this in my solution, you can edit this into my answer if you want – Drdilyor May 08 '23 at 14:40
4

Good news and bad news:

Bad: it's a wontfix, even in pydantic v2: https://github.com/pydantic/pydantic/issues/3120

Good: @adriangb - one of the core devs of pydantic - made a solution, which I translated into a neat decorator. It works for nested models.

Here it goes:

from typing import Optional, Type, Any, Tuple
from copy import deepcopy

from pydantic import BaseModel, create_model
from pydantic.fields import FieldInfo


def partial_model(model: Type[BaseModel]):
    def make_field_optional(field: FieldInfo, default: Any = None) -> Tuple[Any, FieldInfo]:
        new = deepcopy(field)
        new.default = default
        new.annotation = Optional[field.annotation]  # type: ignore
        return new.annotation, new
    return create_model(
        f'Partial{model.__name__}',
        __base__=model,
        __module__=model.__module__,
        **{
            field_name: make_field_optional(field_info)
            for field_name, field_info in model.__fields__.items()
        }
    )

The original code is here.

Usage:

@partial_model
class Model(BaseModel):
    i: int
    f: float
    s: str


Model(i=1)
winwin
  • 958
  • 7
  • 25
  • I got the following error with this decorator: `File "pydantic/json.py", line 90, in pydantic.json.pydantic_encoder / TypeError: Object of type 'ModelField' is not JSON serializable` – danvk Aug 31 '23 at 20:10
  • what is your code? – winwin Aug 31 '23 at 22:18
  • https://github.com/refstudio/refstudio/blob/a92560fcf32e46d599e766708bf930c8bc22860a/python/sidecar/typing.py#L286 – danvk Aug 31 '23 at 22:26
1

This simple trick works for me: build a new model class dynamically and modify fields to be optional as needed.

def make_partial_model(model: Type[BaseModel], optional_fields: Optional[list[str]] = None) -> Type[BaseModel]:
    class NewModel(model):
        ...

    for field in NewModel.__fields__.values():
        if not optional_fields or field in optional_fields:
            field.required = False

    NewModel.__name__ = f'Partial{model.__name__}'
    return NewModel

PartialRequest = cast(Type[RequestModel], make_partial_model(RequestModel))
Namoshizun
  • 51
  • 1
  • 2
1

For Pydantic v2, such a class can be created with create_model(). In v2, required is no longer an attribute of FieldInfo object so you cannot do the trick of field_info.required = False.

from pydantic import BaseModel, create_model

class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float

UpdateItem = create_model(
    'UpdateItem',
    __base__=Item,
    **{k: (v.annotation, None) for k, v in Item.model_fields.items()}
)

Then,

In [410]: Item.model_fields
Out[410]: 
{'name': FieldInfo(annotation=str, required=True),
 'description': FieldInfo(annotation=str, required=True),
 'price': FieldInfo(annotation=float, required=True),
 'tax': FieldInfo(annotation=float, required=True)}

In [411]: UpdateItem.model_fields
Out[411]: 
{'name': FieldInfo(annotation=str, required=False),
 'description': FieldInfo(annotation=str, required=False),
 'price': FieldInfo(annotation=float, required=False),
 'tax': FieldInfo(annotation=float, required=False)}

In [412]: UpdateItem()
Out[412]: UpdateItem(name=None, description=None, price=None, tax=None)
Pieter Ennes
  • 2,301
  • 19
  • 21
jung rhew
  • 800
  • 6
  • 9
  • This is the way for Pydantic V2. I would recommend adding the base model as a parameter to `create_model()` to ensure any model_config is also copied over. – Pieter Ennes Aug 25 '23 at 11:43
  • In this problem, `__base__` is not required and If `UpdateItem` is to be configured or validated differently from the base class `Item`, `__base__` cannot be used together with `__config__` or `__validators__` arguments. So, I'm not sure if I would set `__base__=Item`. – jung rhew Aug 31 '23 at 08:08
0

Modified @Drdilyor's answer

I've made a version that lets you define required arguments in the child class (like the ID of the id of the item you want to update for example) :

class AllOptional(ModelMetaclass):
def __new__(self, name, bases, namespaces, **kwargs):
    annotations = namespaces.get('__annotations__', {})
    for base in bases:
        optionals = {
            key: Optional[value] if not key.startswith('__') else value for key, value in base.__annotations__.items()
        }
        annotations.update(optionals)

    namespaces['__annotations__'] = annotations
    return super().__new__(self, name, bases, namespaces, **kwargs)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
0

Setting fields to Optional is a bit bad though, as it changes your python types. If you ever have a field you would like to be able to set to None via a patch request, you will run into a problem.

For us, using default values works better. Let me explain.

You model would be something like this:

from typing import Optional
from uuid import UUID, uuid4

import pydantic

class PatchPoll(pydantic.BaseModel):
    id: UUID = pydantic.Field(default_factory=uuid4)
    subject: str = pydantic.Field(max_length=1024, default="")
    description: Optional[str] = pydantic.Field(max_length=1024 * 1024, default="")


class Poll(PatchPoll):
    id: UUID
    subject: str = pydantic.Field(max_length=1024)
    description: Optional[str] = pydantic.Field(max_length=1024 * 1024)

You can then use PatchPoll without as many attributes as you like. When it comes to actually applying the patch, make sure you're using __fields_set__ to only update fields which were specified by the client.

>>> PatchPoll()
PatchPoll(id=UUID('dcd80011-e81e-41fb-872b-4f82839a2a76'), subject='', description='')
>>> PatchPoll().__fields_set__
set()
>>> PatchPoll(subject="jskdlfjk").__fields_set__
{'subject'}

I know, it's a little bit of plumbing, but the added value of clean types in python makes it worth it IMHO.

As a bonus, you could even use a function to create the regular versions from the patch version:

def remove_defaults(baseclass: Type[T]) -> Type[T]:
    validators = {"__validators__": baseclass.__validators__}
    fields = baseclass.__fields__

    def remove_default(item: pydantic.fields.ModelField) -> pydantic.fields.FieldInfo:
        info = item.field_info
        if info.default == pydantic.fields.Undefined and not info.default_factory:
            raise RuntimeError("Field has no default")

        # Funny enough, if we don't keep the default for Optional types,
        # openapi-generator will not make it optional at all.
        if item.allow_none:
            return copy.copy(item.field_info)

        return pydantic.Field(
            alias=item.field_info.alias,
            title=item.field_info.title,
            description=item.field_info.description,
            exclude=item.field_info.exclude,
            include=item.field_info.include,
            const=item.field_info.const,
            gt=item.field_info.gt,
            ge=item.field_info.ge,
            lt=item.field_info.lt,
            le=item.field_info.le,
            multiple_of=item.field_info.multiple_of,
            allow_inf_nan=item.field_info.allow_inf_nan,
            max_digits=item.field_info.max_digits,
            decimal_places=item.field_info.decimal_places,
            min_items=item.field_info.min_items,
            max_items=item.field_info.max_items,
            unique_items=item.field_info.unique_items,
            min_length=item.field_info.min_length,
            max_length=item.field_info.max_length,
            allow_mutation=item.field_info.allow_mutation,
            regex=item.field_info.regex,
            discriminator=item.field_info.discriminator,
            repr=item.field_info.repr,
        )

    nondefault_fields = {
        key: (item.type_, remove_default(item)) for key, item in fields.items()
    }

    return pydantic.create_model(
        __model_name=f"{baseclass.__name__}Optional",
        __base__=baseclass,
        __validators__=validators,
        **nondefault_fields,
    )


class PatchPoll(pydantic.BaseModel):
    id: UUID = pydantic.Field(default_factory=uuid4)
    subject: str = pydantic.Field(max_length=1024, default="")
    description: Optional[str] = pydantic.Field(max_length=1024 * 1024, default="")


class Poll(remove_defaults(PatchPoll)):
    ...
Nuschk
  • 518
  • 4
  • 14