full-stack-fastapi-template icon indicating copy to clipboard operation
full-stack-fastapi-template copied to clipboard

How to support FileField with SQLModel?

Open fqzhang42 opened this issue 2 years ago • 4 comments

How to support FileField with SQLModel? I'm aware of sqlalchemy-file, which is for sqlalchemy to handle file field. Can we still use it with SQLModel?

fqzhang42 avatar Jan 30 '24 15:01 fqzhang42

Does this answer resolve your question?

from sqlalchemy import Column, String
from sqlalchemy_file import FileField, FileConverter

from sqlmodel import SQLModel, create_engine, Session

class MyModel(SQLModel):
    __tablename__ = "my_table"

    id = Column(Integer, primary_key=True)
    name = Column(String)
    file = Column(FileField(converter=FileConverter(url="uploads/")))  # Define file field and converter

engine = create_engine("sqlite:///my_database.db")
SQLModel.metadata.create_all(engine)

session = Session(engine)

# Example usage
new_model = MyModel(name="My File", file="path/to/your/file.txt")
session.add(new_model)
session.commit()

session.close()

brunolnetto avatar May 28 '24 12:05 brunolnetto