Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my soft-deletion-honouring model manager be my model's default manager?

Tags:

python

django

I am building soft-deletion functionality for my Django project. I have implemented this using a custom model manager (i.e. performing an initial filter on get_queryset(), plus overriding Model / Manager / QuerySet delete().

Django documentation (1.11):

If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they’re defined in the model) has a special status. Django interprets the first Manager defined in a class as the “default” Manager, and several parts of Django (including dumpdata) will use that Manager exclusively for that model. As a result, it’s a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_queryset() results in an inability to retrieve objects you’d like to work with.

My soft delete-honouring manager is currently my model's default manager (first manager declared on the model class). It's also assigned to objects.

This is convenient for me as a lot of Django code uses the default model manager (e.g. MultipleObjectMixin.get_queryset() if your MultipleObjectMixin-inheriting View just has the model attribute defined).

However the fact that dumpdata also uses the custom model manager has scared me off, and has me thinking about other unknown unintended consequences of setting the default model manager. In the event that I perform a manage.py dumpdata, I'd want my soft-deleted models to be contained in the dump. So I am beginning to doubt myself regarding my choice in overriding the default model manager to filter down the available records.

At the same time, I appreciate the convenience that setting the default model manager is giving me (zero-effort support for generic CBVs.etc), which I want to maintain if possible.

What's the best way to approach this?

like image 740
Kye Russell Avatar asked Nov 29 '18 10:11

Kye Russell


1 Answers

As per this documentation, if you run ./manage.py dumpdata -a or ./manage.py dumpdata --all, then it will dump data using default manager instead of custom manager. If you want to use your default manager instead of custom manager(without changing in models) then you can try like this:

objects = YourModel._base_manager
objects.all()
like image 73
ruddra Avatar answered Nov 08 '22 05:11

ruddra