python - Django admin: SORTING list_display field from reverse FK aggregation -


the model station has fk system. want display station count column in system admin change list. have achieved code below having difficulty making 'num_stations' column sortable.

model.py:

class system(models.model):     pass  class station(models.model):    system_info = models.foreignkey(system) 

admin.py:

class systemadmin(admin.modeladmin):     def num_stations(self, obj):         return obj.station_set.count()      # num_stations.admin_order_field = ????     num_stations.short_description = 'stations'      list_display = (num_stations',) 

the ordinary 'station_set' syntax reverse relationship doesn't seem work in admin_order_field, though other stack overflow question commonly show traversing relation in forward direction supported e.g.

thanks alasdair comment, answer in this question pointed out. here solution fits problem:

class systemadmin(admin.modeladmin):     def num_stations(self, obj):         return obj.num_stations      def get_queryset(self, request):         # def queryset(self, request): # django <1.6         qs = super(systemadmin, self).get_queryset(request)         # qs = super(customeradmin, self).queryset(request) # django <1.6         qs = qs.annotate(num_stations=count('station'))         return qs      num_stations.admin_order_field = 'num_stations'     num_stations.short_description = 'stations'      list_display = ('num_stations', ) 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -