Creating a column to store binary data (Buffer, Byte Array or BLOB) #609
-
First Check
Commit to Help
Example Codefrom typing import Optional
from sqlmodel import Field, SQLModel
class ResidencialBase(SQLModel):
id_cliente: int = Field(index=True)
id_tipo_residencial: int = Field(index=True)
nombre: str = Field(index=True, max_length=50)
telefono_1: str = Field(max_length=15)
telefono_2: Optional[str] = Field(max_length=15)
correo: str = Field(index=True, max_length=255)
direccion: str
logo: bytearray
id_usuario: int
activo: bool
class Residencial(ResidencialBase, table=True):
id_residencial: Optional[int] = Field(default=None, primary_key=True)
class ResidencialCreate(ResidencialBase):
pass
class ResidencialRead(ResidencialBase):
id_residencial: int
class ResidencialUpdate(SQLModel):
id_cliente: Optional[int] = Field(index=True)
id_tipo_residencial: Optional[int] = Field(index=True)
nombre: Optional[str] = Field(index=True, max_length=50)
telefono_1: Optional[str] = Field(max_length=15)
telefono_2: Optional[str] = Field(max_length=15)
correo: Optional[str] = Field(index=True, max_length=255)
direccion: Optional[str]
logo: Optional[bytearray]
id_usuario: Optional[int]
activo: Optional[bool] Description
Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.8 Python VersionPython 3.10.11 Additional ContextTraceback (most recent call last): |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This question is pretty old, but seems to (still) be the first result when looking on how to handle binary data or files with SQLModel, so I'll leave here my solution: from sqlmodel import SQLModel, Column, Field, LargeBinary
class Document(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
filename: str
data: bytes = Field(sa_column=Column(LargeBinary)) the |
Beta Was this translation helpful? Give feedback.
This question is pretty old, but seems to (still) be the first result when looking on how to handle binary data or files with SQLModel, so I'll leave here my solution:
the
sa_column
attribute lets you define columns with SQLAlchemy entities (here,Column
andLargeBinary
are the original SQLALchemy classes re-imported by SQLModel).