RelatedObjectsCollector
is a utility class designed to dynamically collect and paginate related objects of a Django model instance before deletion. It ensures that only objects affected by the on_delete
action (CASCADE
or SET_NULL
) are included. The class helps in notifying users about related objects that will be deleted or modified when the instance is removed.
- Automatically collects related objects for a given Django model instance.
- Filters only the related objects that will be deleted or set to
NULL
. - Wraps collected objects in a
PaginatorObject
to maintain a structured output. - Uses Django's
Paginator
for easy pagination of results. - Provides a clean and structured way to analyze the impact of deletion.
Ensure you have Django installed:
pip install django
from mymodule import RelatedObjectsCollector
from myapp.models import MyModel
instance = MyModel.objects.get(id=1)
collector = RelatedObjectsCollector(instance)
print(collector.data) # Dictionary of related objects
page_number = 1
page = collector.paginator.get_page(page_number)
for obj in page.object_list:
print(obj.data) # Each item contains a related model and its affected objects
A simple wrapper class to store related objects in a way that supports Django’s pagination.
data
: A dictionary containing{model: related_objects}
Responsible for collecting and paginating related objects of a Django model instance.
data
: A dictionary containing{related_model: {on_delete_action: related_objects_queryset}}
paginator
: A DjangoPaginator
instance for paginating the related objects.
__collect_objects()
: Gathers related objects dynamically.__paginator(values)
: Initializes aPaginator
for collected objects.get_on_delete_action(relation)
: Determines theon_delete
behavior (CASCADE
,SET_NULL
).
{
<class 'myapp.models.Book'>: {
"delete": [<Book: Django Mastery>, <Book: Advanced Django>]
},
<class 'myapp.models.Article'>: {
"set_null": [<Article: Python Security>, <Article: Django Tips>]
}
}
This project is open-source and available under the MIT License.