How to convert a list of Pydantic BaseModels to Pandas Dataframe

A quick and dirty profiling yield the following values: from pydantic import BaseModel import pandas as pd from fastapi.encoders import jsonable_encoder class SomeModel(BaseModel): col1: int col2: str data = [SomeModel(col1=1,col2=”foo”),SomeModel(col1=2,col2=”bar”)]*4*10**5 import cProfile cProfile.run( ‘pd.DataFrame([s.dict() for s in data])’ ) # around 3.4s cProfile.run( ‘pd.DataFrame(jsonable_encoder(data))’ ) # around 20.6s cProfile.run( ‘pd.DataFrame([s.__dict__ for s in data])’ ) … Read more

Short way to get all field names of a pydantic class

What about just using __fields__: from pydantic import BaseModel class AdaptedModel(BaseModel): parent_attr: str class TestClass(AdaptedModel): child_attr: str TestClass.__fields__ Output: {‘parent_attr’: ModelField(name=”parent_attr”, type=str, required=True), ‘child_attr’: ModelField(name=”child_attr”, type=str, required=True)} This is just a dict and you could get only the field names simply by: TestClass.__fields__.keys() See model properties: https://pydantic-docs.helpmanual.io/usage/models/#model-properties

Query parameters from pydantic model

The documentation gives a shortcut to avoid this kind of repetitions. In this case, it would give: from fastapi import Depends @app.post(“/test-query-params”) def test_query(model: Model = Depends()): pass This will allow you to request /test-query-params?x=1&y=2 and will also produce the correct OpenAPI description for this endpoint. Similar solutions can be used for using Pydantic models … Read more

FastAPI – GET request results in typeerror (value is not a valid dict)

Pydantic 2 changed how models gets configured, so if you’re using the most recent version of Pydantic, see the section named Pydantic 2 below. SQLAlchemy does not return a dictionary, which is what pydantic expects by default. You can configure your model to also support loading from standard orm parameters (i.e. attributes on the object … Read more

Is it possible to change the output alias in pydantic?

Update (2023-10-07): Check the comments in the question for other answers and this answer in the same question for pydantic 2.0 or newer. Switch aliases and field names and use the allow_population_by_field_name model config option: class TMDB_Category(BaseModel): strCategory: str = Field(alias=”name”) strCategoryDescription: str = Field(alias=”description”) class Config: allow_population_by_field_name = True Let the aliases configure the … Read more

Assigning Pydantic Fields not by alias

As of the pydantic 2.0 release, this behaviour has been updated to use model_config populate_by_name option which is False by default. from pydantic import BaseModel, Field, ConfigDict class Params(BaseModel): var_name: int = Field(alias=”var_alias”) model_config = ConfigDict( populate_by_name=True, ) Params(var_alias=5) # works Params(var_name=5) # works For pydantic 1.x, you need to use allow_population_by_field_name model config option. … Read more

Why do I get “AttributeError: __fields_set__” when subclassing a Pydantic BaseModel?

You need to decide whether to inherit from pydantic.BaseModel, or whether to use the @dataclass decorator (either from dataclasses, or from pydantic.dataclasses). Either is fine, but you cannot use both, according to the documentation (bold face added by myself): If you don’t want to use pydantic’s BaseModel you can instead get the same data validation … Read more

tech