Opened 16 years ago
Closed 15 years ago
#11771 closed (duplicate)
Support filtering by non-database (queryset) fields in the admin
| Reported by: | Samuel Cormier-Iijima | Owned by: | nobody |
|---|---|---|---|
| Component: | contrib.admin | Version: | dev |
| Severity: | Keywords: | admin, filtering, filter, filterspec, fields | |
| Cc: | sciyoshi@…, ramusus@… | Triage Stage: | Accepted |
| Has patch: | yes | Needs documentation: | yes |
| Needs tests: | yes | Patch needs improvement: | yes |
| Easy pickings: | no | UI/UX: | no |
Description
It's currently impossible to filter the admin interface by non-database fields, even if the fields are being selected in the queryset.
The attached patch lets you do something like this:
class Author(models.Model):
name = models.CharField(max_length=255)
class Book(models.Model):
author = models.ForeignKey(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ['name', 'books']
list_filter = [models.IntegerField(verbose_name='number of books', name='num_books')]
def books(self, obj):
return obj.num_books
books.short_description = 'Number of books'
def queryset(self, request):
return super(AuthorAdmin, self).queryset(request).annotate(num_books=models.Count('book'))
admin.site.register(Author, AuthorAdmin)
admin.site.register(Book)
which would show all of the values for num_books in the available filters. (This particular example only works in MySQL, but could be applied to fields selected with .extra(select=...) instead of .annotate).
Attachments (1)
Change History (5)
by , 16 years ago
| Attachment: | 11771.patch added |
|---|
comment:1 by , 16 years ago
comment:2 by , 16 years ago
| Cc: | added |
|---|
comment:3 by , 16 years ago
| Needs documentation: | set |
|---|---|
| Needs tests: | set |
| Patch needs improvement: | set |
| Triage Stage: | Unreviewed → Accepted |
I'll accept the idea of being able to filter on annotated fields, but I don't particularly like the implementation you provide. It strikes me as a whole lot more complex than it should be from an end-users point of view.
Patch also requires tests and documentation.
comment:4 by , 15 years ago
| Resolution: | → duplicate |
|---|---|
| Status: | new → closed |
Forgive me if I'm being presumptuous but it seems like #5833 would encompass this. Closing as dupe.
I totally support your idea, sciyoshi, I just stumbled upon this myself - I added annotation to the queryset method and actually was surprised by the ImproperyConfigured exception. A big request to Django decision makers: please add support for this feature!
By the way, as I am new to the community: Great work, guys! Keep it up!