#29688: ModelAdmin: Add attribute to override manager used by
ModelAdmin.get_queryset()
-----------------------------------------+------------------------
Reporter: Jon Dufresne | Owner: nobody
Type: New feature | Status: new
Component: contrib.admin | Version: master
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-----------------------------------------+------------------------
Use case:
Suppose I have a soft-deletable model. Throughout the application, I want
queries to exclude deleted objects. I do this by overriding the model's
default manager. In the admin, I'd like to be able to edit all objects in
order to undelete them. To do this I might do:
{{{
class ArticleManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(deleted=False)
class Article(models.Model):
...
deleted = models.BooleanField(default=False)
objects = ArticleManager()
}}}
{{{
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
def get_queryset(self):
return Article._base_manager.all()
}}}
However, `ModelAdmin.get_queryset()` is also responsible for
[https://github.com/django/django/blob/3daac76cfbb55acb57c9a8bbfa6f12f766eacc3f/django/contrib/admin/options.py#L349-L359
applying the ordering]. From `django/contib/admin/options.py`:
{{{
def get_queryset(self, request):
qs = self.model._default_manager.get_queryset()
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs
}}}
So to override this method to use a different manager requires duplicating
the ordering logic.
Solution:
I think this can be improved to avoid the duplication by specifying the
manager as an attribute on ModelAdmin. For example, something like:
{{{
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
manager_name = '_base_manager'
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/29688>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/052.dcb6757ec95a6c69c1df42eea20be697%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.