Answer the question
In order to leave comments, you need to log in
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
from django.contrib import admin
class OrderedAdmin(admin.ModelAdmin):
list_display = ('position', 'unordered', )
ordering = ('-unordered', 'position', )
fields = ('position', )
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'
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 questionAsk a Question
731 491 924 answers to any question