Django admin pages: optional queryset fields can be used to sort specific columns

Thus, an additional field in the query set can be used to add additional columns to your selection query, which, in turn, can be set as the default order. I have so far been able to achieve this: I created an additional field, and then set it as the default order.

qs = qs.extra(select={'natname':"concat('0', nat, name)"}, order_by=['natname']) 

Now, in my admin interface, I have other fields {name, nat, location, space, ....} , and the results from the table are ordered by natname when the page is loaded ... excellent.

But now I want to include ordering in the name field, but instead of ordering on name , I want him to order his natname . Is it possible?

So even if natname is an extra field, I want to somehow bind the name column to natname when it comes to ordering.

Right now, if I do qs.query.__str__() , I get a sql request with order by natname . When I click on the name column, order changes to name , but only for this special case, I want him to order his natname . Is it possible?

I watched Django generate headers and views for these automated admin pages under <django-installation-path>/contrib/admin , but it only refers to the list_display set defined in ModelAdmin for this model. If I make any changes, the displayed columns will be changed in the administrative view.

This may seem a bit confusing. If you require specific details, please feel free to ask.

Thanks.

+4
source share
1 answer

Yes! this is possible (at least in Django 1.2.3):

In the subclass admin.ModelAdmin:

 from django.contrib import admin from .models import ClassA class ModelAdminA(admin.ModelAdmin): list_display = ('natname',) def natname(self, obj): return obj.name natname.admin_order_field = 'natname' natname.short_description = 'name' def queryset(self, request): qs = super(ModelAdminA, self).queryset(request) qs = qs.extra(select={ 'natname': "concat('0', nat, name)" }) return qs admin.site.register(ClassA, ModelAdminA) 
+6
source

Source: https://habr.com/ru/post/1338307/


All Articles