2016-02-08 70 views
0

請幫我解決一個問題,我嘗試了很多但不幸的是找不到解決Django管理列表顯示許多排序許多

我的代碼是在

models.py

class MeasuredController(MeasuredObject): 
     ..... 
     tempraturemeasure = models.ManyToManyField(MeasuredTemperature, blank=True, null=True) 
     ..... 


    class MeasuredTemperature(MeasuredObject): 
     ...... 
     temperature = models.DecimalField(max_digits=6,decimal_places=1,verbose_name='Temperature[C]')   ..... 

admin.py

class MeasuredControllerAdmin(admin.ModelAdmin): 
     list_display = ('tem0', 'tem1', 'tem2') 

     def tem2(self, obj): 
      ............... 
      return obj.tempraturemeasure.filter(deviceindex="2").latest("senddate").temperature 
      ....... 

     def tem1(self, obj): 
      ............... 
      return obj.tempraturemeasure.filter(deviceindex="1").latest("senddate").temperature 
      ....... 

     def tem0(self, obj): 
      ............... 
      return obj.tempraturemeasure.filter(deviceindex="0").latest("senddate").temperature 
      ....... 

我的問題將有可能使排序上tem0tem1tem2在管理列

回答

0

您可以通過創建子查詢做到這一點,嘗試這樣

class MeasuredControllerAdmin(admin.ModelAdmin): 
    list_display = ('tem0', 'tem1', 'tem2') 

    def tem2(self, obj): 
     ............... 
     return obj.tempraturemeasure.filter(deviceindex="2").latest("senddate").temperature 
     ....... 

    def tem1(self, obj): 
     ............... 
     return obj.tempraturemeasure.filter(deviceindex="1").latest("senddate").temperature 
     ....... 

    def tem0(self, obj): 
     ............... 
     return obj.tempraturemeasure.filter(deviceindex="0").latest("senddate").temperature 
     ....... 

    def get_queryset(self, request): 
     qs = super(MeasuredControllerAdmin, self).get_queryset(request) 
     qs = qs.extra(
     select = { 
      "tem2" : "<sub query for selecting the latest temp2>"), 
      "tem1" : "<sub query for selecting the latest temp1>"), 
sub query for query for selecting the latest temp1"), 
      "temp0:"<sub query for selecting the latest temp0>")}) 

tem2.admin_order_field = 'tem2' 
tem1.admin_order_field = 'tem1' 
tem0.admin_order_field = 'tem0'