Skip to main content

sqlalchemy-nest

PyPI - Version PyPI - Python Version Downloads CI codecov Maintainability

sqlalchemy-nest is easy create nested models for sqlalchemy

Why?? 🧐🧐

The default constructor of declarative_base() in sqlalchemy is as follows

def _declarative_constructor(self: Any, **kwargs: Any) -> None:
    cls_ = type(self)
    for k in kwargs:
        if not hasattr(cls_, k):
            raise TypeError(
                "%r is an invalid keyword argument for %s" % (k, cls_.__name__)
            )
        setattr(self, k, kwargs[k])

So can’t create nested model by unpacking schema like below. OMG !!!

from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import declarative_base, relationship

Base = declarative_base()

class Root(Base):
    __tablename__ = "root"

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100))

    branches = relationship("Branch", back_populates="root", uselist=True, lazy="joined")

class Branch(Base):
    __tablename__ = "branch"

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100))
    root_id = Column(Integer, ForeignKey("root.id"))

    root = relationship("Root")

root = {
    'name': 'root',
    'branches': [
        {
            'name': 'branch',
        },
    ]
}

created_root = Root(**root)
>>> AttributeError: 'dict' object has no attribute '_sa_instance_state'

Installation

pip install sqlalchemy-nest

Create Nested Model

  1. Set declarative_base constructor

    use declarative_nested_model_constructor for declarative_base constructor

    from sqlalchemy import Column, ForeignKey, Integer, String
    from sqlalchemy.orm import declarative_base, relationship
    from sqlalchemy_nest import declarative_nested_model_constructor
    
    Base = declarative_base(constructor=declarative_nested_model_constructor)
    
    class Root(Base):
        __tablename__ = "root"
    
        id = Column(Integer, primary_key=True, autoincrement=True)
        name = Column(String(100))
    
        branches = relationship("Branch", back_populates="root", uselist=True, lazy="joined")
    
    class Branch(Base):
        __tablename__ = "branch"
    
        id = Column(Integer, primary_key=True, autoincrement=True)
        name = Column(String(100))
        root_id = Column(Integer, ForeignKey("root.id"))
    
        root = relationship("Root")
    
  2. Initialization from **kwargs

    sets attributes on the constructed instance using the names and values in kwargs.

    root = {
        'name': 'root',
        'branches': [
            {
                'name': 'branch',
            },
        ]
    }
    >>> session.add(Root(**root))
    >>> session.commit()
    >>> added_root: Root = session.query(Root).filter(Root.id == 1).first()
    Root(id=1, name='root', branches=[
        Branch(id=1, name='branch', root_id=1)]
    )
    

Merge Nested Model

  1. Set declarative_base constructor and cls

    use declarative_nested_model_constructor and BaseModel for declarative_base

    from sqlalchemy import Column, ForeignKey, Integer, String
    from sqlalchemy.orm import declarative_base, relationship
    from sqlalchemy_nest import declarative_nested_model_constructor
    from sqlalchemy_nest.orm import BaseModel
    
    Base = declarative_base(cls=BaseModel, constructor=declarative_nested_model_constructor)
    
    class Root(Base):
        __tablename__ = "root"
    
        id = Column(Integer, primary_key=True, autoincrement=True)
        name = Column(String(100))
    
        branches = relationship("Branch", back_populates="root", uselist=True, lazy="joined")
    
    class Branch(Base):
        __tablename__ = "branch"
    
        id = Column(Integer, primary_key=True, autoincrement=True)
        name = Column(String(100))
        root_id = Column(Integer, ForeignKey("root.id"))
    
        root = relationship("Root")
    
  2. Update from **kwargs

    root = {
        'name': 'root',
        'branches': [
            {
                'name': 'branch',
            },
        ]
    }
    >>> session.add(Root(**root))
    >>> session.commit()
    >>> added_root: Root = session.query(Root).filter(Root.id == 1).first()
    Root(id=1, name='root', branches=[
        Branch(id=1, name='branch', root_id=1)]
    )
    
    update_root = {
        'id': 1,
        'name': 'updated_root',
        'branches': [
            {
                'id': 1,
                'name': 'updated_branch',
            },
            {
                'name': 'created_branch',
            },
        ]
    }
    >>> added_root.merge(**update_root)
    >>> session.commit()
    >>> updated_root: Root = session.query(Root).filter(Root.id == 1).first()
    Root(id=1, name='updated_root', branches=[
        Branch(id=1, name='updated_branch', root_id=1),
        Branch(id=2, name='created_branch', root_id=1)]
    )
    

Development

Please refer to the CONTRIBUTING

Example

Sample Code using FastAPI and SQLAlchemy

Metadata

Release files for sqlalchemy-nest 1.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sqlalchemy-nest 1.2.3
File Size Uploaded
sqlalchemy_nest-1.2.3.tar.gz 4.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for sqlalchemy-nest 1.2.3
File Interpreter ABI Platform
sqlalchemy_nest-1.2.3-py3-none-any.whl Python 3 none any Details

Total release size: 9.7 kB

Release files / sqlalchemy_nest-1.2.3.tar.gz

Download URL sqlalchemy_nest-1.2.3.tar.gz
Size 4.5 kB
Tags Source
SHA-256 checksum
How to use checksums
824a576beda2b784b6e2f0cf1da03678666cfd5b2e394828c6a664725715858d
BLAKE2b-256 checksum
How to use checksums
6e15ec20b9970fe2c8f7dedcdd0f786b592614e235c1f2c7260f6a7ffd51dbbe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.11.0 Linux/6.11.0-1018-azure

Release files / sqlalchemy_nest-1.2.3-py3-none-any.whl

Download URL sqlalchemy_nest-1.2.3-py3-none-any.whl
Size 5.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ff218b174456030df128e5a94286700443cb231f25e6472be5a886ab51ff7b36
BLAKE2b-256 checksum
How to use checksums
1cbb1c2b93a87c50e1d9c424c8906ba40377ce84de38050e57917c9e9e8143ec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.11.0 Linux/6.11.0-1018-azure

Release history Release notifications | RSS feed

This release

1.2.3 This release

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.5

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page