#πŸ”’ Unable to use SQLAlchemy models without Sessions

4 messages Β· Page 1 of 1 (latest)

iron mauve
#

Hi,
Eariler, I was using Dataclasses and Raw SQL queries to manage data and interact with database. However, this meant, if there was a change in database schema or data, it would need to be edited in two places.

Then I heard about SQLAlchemy and thought that SQLAlchemy models (defined by extending declarative base) would be perfect. So I replaced my dataclasses and raw SQL with SQLAlchemy.

I have a class called db_handler. I use it to create a single object and then call the object's functions to perform CRUD operations. This way, the rest of the code doesn't know if the models are pydantic, or dataclasses or SQLAlchemy models, they worked perfectly. Similarly, the code was not bothered if I was using raw SQL queries or SQLAlchemy - it was purely managed by db_handler class.

That's what I thought. However, I was testing the db_handler, and after I committed the model object, it became unusable.

Here's the testing code:

p = Person(name = "John", age=54) # p.name and p.age accessible here
db_handler.add_person(p)
print(p.name) # ERROR - Instance <Person at 0x... is not bound to a Session; attribute refresh cannot proceed.

Here's the code for add_person:

def add_person(self, p: Person):
    session = self.Session() # Session = sessionmaker(self.engine)
    session.add(p)
    session.commit()
    session.expunge(p)

Earlier, I was using self.Session.begin() with a context manager, but after scrolling the internet, it seemed like we need to remove the object from session. But, I'm still getting the error about Object not being bound to session.

ChatGPT is suggesting me to use a modelDTO (using dataclasses)- but that would defeat my purpose of single model.

scenic bladeBOT
#

@iron mauve

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

scenic bladeBOT
#

@iron mauve

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.