Convert a SqlAlchemy query object to a dict(json)
Project description
Convert a SqlAlchemy query object to a dict(json)
Install
pip install aljson
Usage
from aljson import BaseMixin
# The Sqlalchemy model
class Parent(Base, BaseMixin):
__tablename__ = 'parent'
id = sa.Column(sa.Integer, primary_key=True, unique=True)
name = sa.Column(sa.String(64))
# query Parent model
print(result.to_json())
Full example
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from aljson import BaseMixin
import sqlalchemy as sa
Base = declarative_base()
class Parent(Base, BaseMixin):
__tablename__ = 'parent'
id = sa.Column(sa.Integer, primary_key=True, unique=True)
name = sa.Column(sa.String(64))
class Child(Base, BaseMixin):
__tablename__ = 'child'
id = sa.Column(sa.Integer, primary_key=True, unique=True)
name = sa.Column(sa.String(64))
parent_id = sa.Column(sa.Integer, sa.ForeignKey('parent.id'))
parent = relationship("Parent")
# Create an engine that stores data in the local directory's
# sqlalchemy_example.db file.
engine = sa.create_engine('sqlite:///my_database.sqlite')
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)
session = DBSession()
# Create a new parent and a child
new_parent = Parent()
new_parent.name = "parent_1"
new_child = Child()
new_child.name = "child_1"
new_child.parent = new_parent
session.add(new_parent)
session.add(new_child)
session.commit()
# Search for a row
query_result = session.query(Child).first()
# And you can call .to_json
print(query_result.to_json())
# The result should be like this:
# {'id': 1, 'name': 'child_1', 'parent_id': 1, 'parent': {'id': 1, 'name': 'parent_1'}}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
aljson-0.3.0.tar.gz
(2.4 kB
view details)
File details
Details for the file aljson-0.3.0.tar.gz
.
File metadata
- Download URL: aljson-0.3.0.tar.gz
- Upload date:
- Size: 2.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.42.0 CPython/3.7.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b7a11c65ced9901469390c3e42f74afc2db8def739946b242500c6815627194a |
|
MD5 | 384b0289e983d9e1009e2404ddda0b21 |
|
BLAKE2b-256 | d76cdaba09d0a7efa3927ce286da0117e07941c09287226a1d9e467ce6fce907 |