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.6.2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 52998bf80ecab7b257b17299966c0b7ef93c31906bb9252603e4307274ba2722 |
|
MD5 | d7704d4872043ed6f13806c17680b1ef |
|
BLAKE2b-256 | dc599b8e085edb87700cbb8c58f5180b288754f13931036f5dddad332165dfca |
Hashes for sqlalchemy_easy_softdelete-0.6.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ee8ff49b1b31f26ec40cd4401e5eb0e593a91e13d5f8ac88869baf55ae8d175c |
|
MD5 | e2e14e2ae7b4b42ab3fa0b2555a812d5 |
|
BLAKE2b-256 | 005e1bc70cd7eb2b67f8746e6776599df3c5b27719dd040aeefd306c3ce703f1 |