Django

Code

Ticket #11771 (new)

Opened 7 months ago

Last modified 2 months ago

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

Reported by: sciyoshi Assigned to: nobody
Milestone: Component: django.contrib.admin
Version: SVN Keywords: admin, filtering, filter, filterspec, fields
Cc: sciyoshi@gmail.com, ramusus@gmail.com Triage Stage: Accepted
Has patch: 1 Needs documentation: 1
Needs tests: 1 Patch needs improvement: 1

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

11771.patch (1.7 kB) - added by sciyoshi on 08/22/09 23:51:04.

Change History

08/22/09 23:51:04 changed by sciyoshi

  • attachment 11771.patch added.

11/22/09 08:24:16 changed by kris_b

  • needs_better_patch changed.
  • needs_tests changed.
  • needs_docs changed.

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!

11/28/09 11:57:56 changed by anonymous

  • cc changed from sciyoshi@gmail.com to sciyoshi@gmail.com, ramusus@gmail.com.

02/03/10 08:00:41 changed by russellm

  • needs_better_patch set to 1.
  • stage changed from Unreviewed to Accepted.
  • needs_tests set to 1.
  • needs_docs set to 1.

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.


Add/Change #11771 (Support filtering by non-database (queryset) fields in the admin)




Change Properties
Action