database commit action changed unrelated model variable state #9231
-
|
The If you see my edit records, the first version, pytest show where occur the error Code import asyncio
from typing import Any
from sqlalchemy import Boolean, Column, Integer, String, ForeignKey, select
from sqlalchemy.orm import as_declarative
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, async_sessionmaker, AsyncSession as Session
from sqlalchemy.pool import NullPool
engine: AsyncEngine = create_async_engine(
"postgresql+asyncpg://python:changethis@localhost:5432/fastapi", pool_pre_ping=True, poolclass=NullPool)
SessionLocal = async_sessionmaker(autoflush=True, bind=engine)
@as_declarative()
class Base:
id: Any
__name__: str
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()
class User(Base):
id = Column(Integer, primary_key=True, index=True)
full_name = Column(String, index=True)
email = Column(String, unique=True, index=True, nullable=False)
hashed_password = Column(String, nullable=False)
is_active = Column(Boolean(), default=True)
is_superuser = Column(Boolean(), default=False)
items = relationship("Item", back_populates="owner")
class Item(Base):
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)
owner_id = Column(Integer, ForeignKey("user.id"))
owner = relationship("User", back_populates="items")
async def test_query_item(db: Session):
statm = select(User).where(User.id == 1)
result = await db.execute(statm)
user = result.first()[0]
statm = select(Item).where(Item.owner_id == user.id)
result = await db.execute(statm)
item = result.first()[0]
await db.commit()
await db.refresh(item)
assert item.owner_id == user.id
asyncio.run(test_query_item(SessionLocal()))error dependencies
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
hi there basically, don't ever use this pattern, it is very wasteful and does not regenerate lazy-loaded relationships, nor in this case is it refreshing your user object: do this instead see the second bullet at https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#preventing-implicit-io-when-using-asyncsession |
Beta Was this translation helpful? Give feedback.
hi there
basically, don't ever use this pattern, it is very wasteful and does not regenerate lazy-loaded relationships, nor in this case is it refreshing your user object:
do this instead
see the second bullet at https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#preventing-implicit-io-when-using-asyncsession