Models
Pydantic Docs · docs.pydantic.dev [1]
I came accross from_attributes today it allows creation of pydantic models from objects such as a sqlalchemy Base Model or while nesting pydantic models. I believe in the past I have ran into some inconsistencies with nesting pydantic models and I’ll bet one had from_attributes set and another did not.
Arbitrary class instances¶
(Formerly known as “ORM Mode”/from_orm).
Pydantic models can also be created from arbitrary class instances by reading the instance > attributes corresponding to the model field names. One common application of this functionality is integration with object-relational mappings (ORMs).
To do this, set the from_attributes config value to True (see the documentation on Configuration for more details).
The example here uses SQLAlchemy, but the same approach should work for any ORM.
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://docs.pydantic.dev/latest/concepts/models/#rebuilding-model-schema
[2]: /thoughts/
Posts tagged: pydantic
All posts with the tag "pydantic"
3 posts
latest post 2025-01-28
Publishing rhythm
Fields
Pydantic Docs · docs.pydantic.dev [1]
exclude=True and repr=False is a good pydantic combination for secret attributes such as user passwords, or hashed passwords. exclude keeps it out of model_dumps, and repr keeps it out of the logs.
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(repr=True)
age: int = Field(repr=False)
user = User(name='John', age=42)
print(user)
#> name='John'
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://docs.pydantic.dev/2.7/concepts/fields/#field-representation
[2]: /thoughts/
External Link
stackoverflow.com [1]
I went down the route of leveraging the json-enc extention in htmx [2], but later realized that this completely breaks browsers/users who do not wish to use javascript. While most of the web would feel quite broken with javascript disabled, I don’t want to contribute to that without good reason.
Taking a second look into this issue, rather than using json-enc, and using as_form to get form data into a model keeps the nice DX fo everything being a pydantic model, but the site still works without js. with js htmx kicks in, you get a spa like experience by loading partials onto the page, and without, you just get a full page reload.
the implementation # [3]
copied from https://stackoverflow.com/questions/60127234/how-to-use-a-pydantic-model-with-form-data-in-fastapi
import inspect
from typing import Type
from fastapi import Form
from pydantic import BaseModel
from pydantic.fields import ModelField
def as_form(cls: Type[BaseModel]):
new_parameters = []
for field_name, model_field in cls.__fields__.items():
model_field: ModelField # type: ignore
new_parameters.append(
inspect.Parameter(
model_field.alias,
inspect.Parameter.POSITION...
global Field
global BaseModel
from pydantic import BaseModel
from pydantic import Field
Pydantic is a Python library for serializing data into models that can be
validated with a deep set of built in valitators or your own custom validators,
and deserialize back to JSON or dictionary.
Installation # [1]
To install pydantic you will first need python and pip. Once you have pip
installed you can install pydantic with pip.
pip install pydantic
Always install in a virtual environment [2]
Creating a Pydantic model # [3]
To get started with pydantic you will first need to create a Pydantic model.
This is a python class that inherits from pydantic.BaseModel.
from pydantic import BaseModel
from pydantic import Field
from typing import Optional
class Person(BaseModel):
name: str = Field(...)
age: int
parsing an object # [4]
person = Person(name="John Doe", age=30)
print(person)
name='John Doe' age=30
data serialization # [5]
Pydantic has some very robust serialization methods that will automatically
coherse your data into the type specified by the type-hint in the model if it can.
person = Person(name=12, age="30")
print(f'name: {person.name}, type: {type(person.name)}')...