Comments (6)
You can achieve the desired functionality like this:
from sqlmodel import Session as SQLModelSession
from contextlib import contextmanager
engine = ...
@contextmanager
def Session():
session = SQLModelSession(engine)
try:
yield session
finally:
session.close()
Then, you can use Session
as a context manager without passing the engine every time:
with Session() as session:
...
from sqlmodel.
Why do you want a sessionmaker instead of using the new/future and more modern approach of using a
with
statement with aSession
?
My understanding is that the point of the sessionmaker is so that you don't have to pass the configuration (e.g. the engine) to the Session every time. https://docs.sqlalchemy.org/en/14/orm/session_basics.html#using-a-sessionmaker
from sqlmodel.
I faced the same issue and it looks like SQLAlchemy's sessionmaker
works just fine with sqlmodel. The only caveat is that you have to provide sqlmodel.Session
class to it:
from sqlmodel import Session
from sqlalchemy.orm import sessionmaker
TestSession = sessionmaker(class_=Session)
from sqlmodel.
Why do you want a sessionmaker instead of using the new/future and more modern approach of using a with
statement with a Session
?
Just for completeness, AFAIK, the sessionmaker exists mainly because there was no with
statement at the time.
from sqlmodel.
I faced a similar issue when I tried to call session.exec
,then I got an error
AttributeError: 'Session' object has no attribute 'exec'
I found that if you use Sessionmaker like the below, you will get an instance of sqlalchemy.orm.session.Session
instead of sqlmodel.orm.session.Session
, and the instance of the SQLAlchemy session doesn't have the method exec
, only the SQLModel session has.
from sqlalchemy.orm import sessionmaker
SessionLocal = sessionmaker(autoflush=False , bind=engine)
to fix the issue, just like @olzhasar mentioned, you have to pass Session
that is imported from sqlmodel and pass to sessionmaker
from sqlmodel import Session as SQLModelSession
SessionLocal = sessionmaker(class_ = SQLModelSession, autoflush=False , bind=engine)
def get_session():
with SessionLocal() as session:
yield session
Session = Annotated[SQLModelSession, Depends(get_session)]
# endpoint
@router.get("/db-test")
async def db_test(session: Session):
statement = select(User)
results = session.exec(statement)
user = results.first()
return user
from sqlmodel.
Please add this because now it give error that .exec() does not exist on session if you using sqlalchemy import.
from sqlmodel.
Related Issues (20)
- `enum.IntFlag` field error when the flag is zero or many field enabled. HOT 1
- The SQL model cannot perform insertion into another table using queried data HOT 2
- not autocompletion
- Could not refresh instance HOT 10
- SQLModel doesn't recognize Relationship between models HOT 1
- Get select with options (selectinload) using response schema HOT 3
- Dose there any better way to write timezone aware datetime field without using the SQLAlchemy ? HOT 3
- Obtaining `TypeError: Cannot pickle 'module' object` on models with many-to-many relationships HOT 2
- Order of columns in the table created does not have 'id' first, despite the order in the SQLModel. Looks like it's prioritising fields with sa_column HOT 6
- Erro ao executar uvicorn.run(...) HOT 1
- Many to many relationship between a table and itself HOT 6
- How to add current date time by default on a table declaration? HOT 13
- Add documentation about how to use the async tools (session, etc) HOT 7
- async relationship bug HOT 14
- 🚀 Roadmap HOT 33
- Internal link failed at create-db-and-table.md
- Field cannot autocompletion when its a SQLModel HOT 7
- Add an overload to the `exec` method with `_Executable` statement for update and delete statements HOT 5
- How to define table prefix name
- docs/contributing.md outdated using poetry HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from sqlmodel.