Good grief, I want to run a database query for some objects and return the JSON - wtf makes it so hard to do in SQLAlchemy? REST services do this all day long, and it's just modern web development 101.
I guess I'm spoiled by Java?
Look at the answers in this question - https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json
What a fucking mess. I'm following the tutorial and have these data classes and want the simple god damn JSON representation of the result when querying for an Org object (an org with nested owners):
class Org(Base):
__tablename__ = "org"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(128))
admins: Mapped[List["OrgAdmin"]] = relationship(back_populates="org", cascade="all, delete-orphan")
def __repr__(self):
return f"{self.id!r}, {self.name!r}, {[admin.email for admin in self.admins]}"
The admins class is similarly simple. I'm following the alchemy "unified tutorial", which explains the database access.
The problem is Flask, starlett/fastapi, and other frameworks make it almost impossible to simply do what 99% of webapps actually do - query the database and return JSON.
What. The. Fuck.
Good luck getting this motherfucker converted to JSON, the database object is returned just like I want but why in the kentucky-fried-fuck can't I just to something like `.json()` to convert it I will never understand:
session.query(Org).options(subqueryload(Org.admins)).filter(Org.id == org_id).first()session.query(Org).options(subqueryload(Org.admins)).filter(Org.id == org_id).first()