7

I have the following django admin exceprt:

class TagAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}
    list_display = ['title', 'total_videos', 'total_active_videos', 'weight', 'status']
    search_fields = ['title']
    list_filter = ['status']
    ordering = ['-weight']

    def queryset(self, request):
        return Tag.objects.annotate(total_videos_order=Count('video'))

    def total_videos(self, obj):
        return obj.total_videos_order
    total_videos.admin_order_field = 'total_videos_order'

    def total_active_videos(self, obj):
        return u'%s' % Video.objects.filter(tags=obj, status=Video.STATUS_ACTIVE).count()

Now this all works fine and both total_videos and total_active_videos are showing the right information. Also total_videos is sortable if you click on the table header. However if I try to change the code to:

ordering = ['total_videos_order']

I receive an error:

TagAdmin.ordering[0]' refers to field 'total_videos_order' that is missing from model 'videos.Tag'.

Same if its just "total_videos". As a workaround I can ignore that and just click on the header but it bothers my why, if its ordered via clicking the default order cannot be set, when the field obviously exists? Any ideas on that?

Second part of the question is if its possible to add a sort on the filtered field "total_active_videos". From what I understand its not possible to annotate with conditions so it cant be done the same way its done for "total_videos" but are there any other solutions?

Thanks!

jproffitt
  • 6,225
  • 30
  • 42
Feras
  • 2,114
  • 3
  • 20
  • 42
  • How is `total_videos_order` defined on your model? Is it a regular field, or is it some computed value? Have a look at [this answer](http://stackoverflow.com/a/15935591/58107). It uses an annotated value, which can be used by the admin to do a sort on. – Bouke Jan 13 '14 at 20:42
  • I use most of the code from the answer, unfortunately it doesnt solve my issue. – Feras Jan 21 '14 at 07:12
  • 1
    There are more pointers in my comment, please address them. – Bouke Jan 21 '14 at 21:03

0 Answers0