Easily add soft-deletion to your SQLAlchemy Models.
Project description
SQLAlchemy Easy Soft-Delete
Easily add soft-deletion to your SQLAlchemy Models and automatically filter out soft-deleted objects from your queries and relationships.
This package can generate a tailor-made SQLAlchemy Mixin that can be added to your SQLAlchemy Models, making them contain a field that, when set, will mark the entity as being soft-deleted.
The library also installs a hook which dynamically rewrites all selects which are sent to the database for all tables that implement the soft-delete mixin, providing a seamless experience in both manual queries and model relationship accesses.
Mixin generation is fully customizable and you can choose the field name, its type, and the presence of (soft-)delete/undelete methods.
The default implementation will generate a deleted_at
field in your models, of type DateTime(timezone=True)
, and will also provide a .delete(v: Optional = datetime.utcnow())
and .undelete()
methods.
Installation:
pip install sqlalchemy-easy-softdelete
How to use:
from sqlalchemy_easy_softdelete.mixin import generate_soft_delete_mixin_class
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer
from datetime import datetime
# Create a Class that inherits from our class builder
class SoftDeleteMixin(generate_soft_delete_mixin_class()):
# type hint for autocomplete IDE support
deleted_at: datetime
# Apply the mixin to your Models
Base = declarative_base()
class Fruit(Base, SoftDeleteMixin):
__tablename__ = "fruit"
id = Column(Integer)
Example Usage:
all_active_fruits = session.query(Fruit).all()
This will generate a query with an automatic WHERE fruit.deleted_at IS NULL
condition added to it.
all_fruits = session.query(Fruit).execution_options(include_deleted=True).all()
Setting include_deleted=True
(attribute name can be customized) in the query disables soft delete for that query.
License
- BSD-3-Clause
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
Built Distribution
Hashes for sqlalchemy-easy-softdelete-0.4.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | aa6eba20be0310fd4c372b044cbd4c8d258776266b2d78854e773b98f8daf53b |
|
MD5 | 23d72e1d2f982296e3bc69b61961a098 |
|
BLAKE2b-256 | 432df79929c94fddb61a534e7c6a18450aa1e7bcab5784c8dfaf43b5b525e764 |
Hashes for sqlalchemy_easy_softdelete-0.4.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4d2d28574ad692f598ccede72a06d2ce238a07fe45a1feec657adfa3b0b9f912 |
|
MD5 | 655eb2845ada8c7cb23980d9b471c5d4 |
|
BLAKE2b-256 | 426ae85925f2238b6c8ea2f2a4fb4287d9f5527012989ea42339e9bf2605464f |