How to convert user input to snake_case using Pydantic base model?

82 views Asked by At

I have a pydantic BaseModel which looks like:

class BookCreation(BaseModel):
    book_name: str
    book_size: Optional[str]
    book_author: str

Now, when the user passes the an input with inconsistent case as below:

{
    "book_name": "new-book",
    "book_SIZE": "23",
    "book_author": "test value"
}

Now this inputs is treated as if it has only two valid attributes i.e, book_name and book_author and book_size is assigned to None.

How do I ensure that the input changes to snake_case when I parse the input?

1

There are 1 answers

0
Axel Donath On

You can user alias generators for this. See the following example:

from pydantic import BaseModel, ConfigDict
from typing import Optional


def to_lower(string: str) -> str:
    return string.lower()

    
class BookCreation(BaseModel):
    model_config = ConfigDict(alias_generator=to_lower)
    book_name: str
    book_size: Optional[str] = None
    book_author: str


data = {
    "book_name": "new-book",
    "book_SIZE": "23",
    "book_author": "test value"
}

print(BookCreation.model_validate(data))

Which prints:

book_name='new-book' book_size=None book_author='test value'

Depending on your use case you can adapt the to_lower function to handle whatever convention you might want to support.

I hope this helps!