Opened 7 years ago

Closed 6 years ago

#11771 closed (duplicate)

Support filtering by non-database (queryset) fields in the admin

Reported by: sciyoshi Owned by: nobody
Component: contrib.admin Version: master
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: UI/UX:


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')), AuthorAdmin)

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)

11771.patch (1.7 KB) - added by sciyoshi 7 years ago.

Download all attachments as: .zip

Change History (5)

Changed 7 years ago by sciyoshi

comment:1 Changed 7 years ago by kris_b

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

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!

comment:2 Changed 7 years ago by anonymous

  • Cc ramusus@… added

comment:3 Changed 7 years ago by russellm

  • Needs documentation set
  • Needs tests set
  • Patch needs improvement set
  • Triage Stage changed from Unreviewed to 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 Changed 6 years ago by subsume

  • Resolution set to duplicate
  • Status changed from new to closed

Forgive me if I'm being presumptuous but it seems like #5833 would encompass this. Closing as dupe.

Note: See TracTickets for help on using tickets.
Back to Top