Django admin default ordering of custom fields
Asked Answered
L

0

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!

Lambskin answered 7/11, 2013 at 4:12 Comment(3)
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. It uses an annotated value, which can be used by the admin to do a sort on.Clough
I use most of the code from the answer, unfortunately it doesnt solve my issue.Lambskin
There are more pointers in my comment, please address them.Clough

© 2022 - 2024 — McMap. All rights reserved.