Admin, order by aggregate count?

148 views
Skip to first unread message

none

unread,
Nov 10, 2010, 11:38:27 PM11/10/10
to django-taggit
I was able to display the number of times a tag was used for a
specific content type, however, I am not able to sort the admin list
by this number. This is what I have so far. Any suggestions?

from django.contrib import admin
from taggit.models import Tag, TaggedItem
from django.contrib.contenttypes.models import ContentType
from posts.models import Post

class TaggedItemInline(admin.StackedInline):
model = TaggedItem


def posts_count(obj):
posts_count = TaggedItem.objects.filter(
tag=obj, content_type=ContentType.objects.get_for_model(Post)
).count()
return posts_count

posts_count.short_description = 'Post Count'


class TagAdmin(admin.ModelAdmin):

list_display = ('name', 'slug', 'is_category', posts_count)
list_filter = ('is_category',)
search_fields = ['name',]

inlines = [
TaggedItemInline
]


admin.site.register(Tag, TagAdmin)

Carl Meyer

unread,
Nov 11, 2010, 9:30:56 AM11/11/10
to django...@googlegroups.com
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

none wrote:
> I was able to display the number of times a tag was used for a
> specific content type, however, I am not able to sort the admin list
> by this number. This is what I have so far. Any suggestions?

Sorting happens in the database, so you can only sort by a value that
exists in the database as a column on that table, or else using an
aggregate query.

If you need to sort by this field using the admin's built-in sort
toggles, you will have to actually create an IntegerField on a custom
tag model and store the updated post count in that field whenever a tag
is used.

If you can be satisfied with having the default sort be by post count,
but not be able to use sort toggles on the column header, you could
override the queryset() method of the ModelAdmin, add a post-count
aggregate to the queryset and order by it.

Carl
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkzb/iAACgkQFRcxmeyPUXITnQCfb4re++6WxW+V2sahYaoEoBcl
GpgAn3kTj287rnWDSWQE/o5UGTcdNVjM
=ZoUI
-----END PGP SIGNATURE-----

and...@gmail.com

unread,
Aug 19, 2016, 11:26:38 AM8/19/16
to django-taggit
A very old thread but I thought I'd post an solution for cases where you can use ORM aggregates. I found this blog post: http://blog.endpoint.com/2013/09/getting-django-admin-to-sort-modified.html

(note - since this article was published get_query_set has changed to get_queryset)

Reply all
Reply to author
Forward
0 new messages