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
PaginatorObjectto maintain a structured output. - Uses Django's
Paginatorfor easy pagination of results. - Provides a clean and structured way to analyze the impact of deletion.
Ensure you have Django installed:
pip install djangofrom mymodule import RelatedObjectsCollector
from myapp.models import MyModel
instance = MyModel.objects.get(id=1)
collector = RelatedObjectsCollector(instance)print(collector.data) # Dictionary of related objectspage_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 objectsA 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 DjangoPaginatorinstance for paginating the related objects.
__collect_objects(): Gathers related objects dynamically.__paginator(values): Initializes aPaginatorfor collected objects.get_on_delete_action(relation): Determines theon_deletebehavior (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.