Skip to content

sqlalchemy.orm.exc.DetachedInstanceError #12

@mauphung

Description

@mauphung

Please help me to make solve this error of my ftest1.py due to sqlalchemy.orm.exc.DetachedInstanceError. I cannot restore session entity and currentcy.

from python_accounting.config import config
from python_accounting.models import Base
from sqlalchemy import create_engine, inspect

database = config.database
engine = create_engine(database["url"])

Base.metadata.create_all(engine) # run migrations to create tables

from python_accounting.database.session import get_session
from python_accounting.models import Entity, Currency

with get_session(engine) as session:
entity = Entity(name="Example Company")
session.add(entity)
session.commit() # This automatically sets up a Reporting Period for the Entity

if(inspect(entity).session):
    print("add session entity SUCCESS")
else:
    print("add session entity FAILED")

currency = Currency(name="US Dollars", code="USD", entity_id=entity.id)
session.add(currency)
session.commit()

if(inspect(entity).session):
    print("add session currency SUCCESS")
else:
    print("add session currency FAILED")

from python_accounting.models import Account
tax_account = Account(
name="Tax Account",
account_type=Account.AccountType.CONTROL,
currency_id=currency.id, # <====. line 36 ERROR: session currency expired
entity_id=entity.id,
)
"""
OUTPUT:
add session entity SUCCESS
add session currency SUCCESS


Traceback (most recent call last):
File "/test/test1.py", line 36, in
currency_id=currency.id,
^^^^^^^^^^^
sqlalchemy.orm.exc.DetachedInstanceError: Instance <Currency at 0x103bcc050> is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: https://sqlalche.me/e/20/bhk3)
"""

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions