-
-
Notifications
You must be signed in to change notification settings - Fork 664
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Could not refresh instance #536
Comments
database is mysql |
del session.refresh(item) |
@JeseYe thanks but I want to know why session.refresh not refresh item. |
You cannot refresh the item because there is no database instance connected with it.
|
I'm running into this problem myself as well. Pardon my ignorance, but shouldn't SQLModel do this for us? Or is this just something that must be done when using MySQL (assuming this isn't a problem for other DB types)? |
I discovered a solution for this: As it turns out, the object I was passing to the REST endpoint had an ID specified (the ID was 0). When I either don't specify an ID or set it to None prior to adding/committing/refreshing then everything works as desired.
|
Although... again... shouldn't SQLModel (or FastAPI?) determine that since
|
Depends on what the default value in the Item schema is, whether 0 or None. However, we shouldn't be having to do this. Using an if condition to check for an id that is passed from a request seems like hacky fix to this problem. If the id is set as the primary key in the models it should be auto incremented by the orm. |
I also have this (or, rather, a similar) issue. But in my case I do have both defaults that are not none, and a record with the same primary key in DB. Code that doesn't work (right now at least)Modelsimport uuid
import pydantic
from sqlmodel import Field, Relationship, SQLModel
from .faculty import FacultyModel
class CreateDepartment(SQLModel):
name: str = Field(unique=True, index=True)
description: str | None = Field(default=None, nullable=True)
class DepartmentRepresentation(BaseDepartment):
department_id: pydantic.UUID4
faculties: list[FacultyModel]
class DepartmentModel(BaseDepartment, table=True):
"""
Describes a department in an educational institution.
Highest level of organization in an educational institution.
Departments have a list of associated faculties.
"""
department_id: pydantic.UUID4 = Field(
default_factory=uuid.uuid4,
primary_key=True,
index=True,
)
faculties: list[FacultyModel] = Relationship(back_populates="department") EndpointCode sample: @admin_router.put(
"/department/{department_id}",
description="Update a department",
)
async def update_department(
db: Annotated[database_session_type, Depends(database_session)],
department_id: str,
department: Annotated[CreateDepartment, Body()],
_: Annotated[DepartmentModel, Depends(department_exists)],
) -> DepartmentRepresentation:
department_obj = DepartmentModel.model_validate(department)
department_obj.department_id = department_id
return update_entity(
db=db,
entity=department_obj,
) Basically - it takes in the model for a department, and spits out it's representation from the database by performing an update. Update callfrom sqlalchemy.exc import IntegrityError, InvalidRequestError
from sqlmodel import Session, SQLModel
from samurai_backend.errors import SamuraiIntegrityError
...
def update_entity(
db: Session,
entity: SQLModel,
) -> SQLModel:
try:
db.add(entity)
db.commit()
db.refresh(entity)
return entity
except (IntegrityError, InvalidRequestError) as e:
db.rollback()
raise SamuraiIntegrityError from e ErrorI get exception
There's a lengthy INSERT SQL query, which is performed in Code that does work (right now)Update the from sqlalchemy.exc import IntegrityError, InvalidRequestError
from sqlmodel import Session, SQLModel, update
from samurai_backend.errors import SamuraiIntegrityError
...
def update_entity(
db: Session,
entity: SQLModel,
primary_key: str,
) -> SQLModel:
try:
entity_class = entity.__class__
update_query = (
update(entity_class)
.where(getattr(entity_class, primary_key) == getattr(entity, primary_key))
.values(**entity.model_dump(exclude={primary_key}))
)
db.exec(update_query)
db.commit()
return entity
except (IntegrityError, InvalidRequestError) as e:
db.rollback()
raise SamuraiIntegrityError from e Right now I see this as my only solution, but if you have different ideas, please, let me (or, rather - us) know. P.S. Just using refresh won't do, since then you will get an error that this object is not in registry yet. Thanks! Additional infoI'm using sqlmodel 0.0.16, the latest version at the moment of writing this comment. |
had a similar issue, setting auto_increment=True on primary_key id solved it |
First Check
Commit to Help
Example Code
Description
In sql model documentation I saw an example of session.refresh() but when I am trying to implement this in my fastapi project this not working and raise exception that is could not refresh instance and also I am trying to print item.id, this is not also working, raise exception that is expired.
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.8
Python Version
3.10.6
Additional Context
raise sa_exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: Could not refresh instance '<Server at 0x7f69b549f500>'
The text was updated successfully, but these errors were encountered: