I
I
Icic Bender2016-07-17 15:28:18
Django
Icic Bender, 2016-07-17 15:28:18

How to make admin panel sort by virtual field by default?

models.py:

from django.db import models

class Ordered(models.Model):
    position = models.PositiveSmallIntegerField(
        'Позиция',
        null = True,
        blank = True
    )

    def unordered(self):
        return self.position == None

admin.py:
from django.contrib import admin

class OrderedAdmin(admin.ModelAdmin):
    list_display = ('position', 'unordered', )
    ordering = ('-unordered', 'position', )
    fields = ('position', )

Dzhanga returns an error (admin.E033), saying that the model does not have an unordered attribute.
If ordering is removed , then in the admin panel we will see the unordered column .
You can still force sorting by virtual parameter by changing admin.py:
from django.contrib import admin

class OrderedAdmin(admin.ModelAdmin):
    list_display = ('position', 'is_unordered', )
    fields = ('position', )

    def get_queryset(self, request):
        qs = super(OrderedAdmin, self).get_queryset(request)
        qs = qs.annotate(is_unordered = models.Count('position'))
        return qs

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

In the admin panel, it becomes possible to sort the is_unordered column , however, returning Jang will throw the same error again. Task: so that the admin panel sorts by default like this: first, all elements with position , sorted in ascending order, and then all the rest.
ordering = ('-is_unordered', 'position', )

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question