jai prakash Singh February 2016

django admin list display sorting from many to many

please help me in solving an issue i tried a lot but unfortunately could not find the solution

my code is under

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
            .......

my question will it possible to make a sorting on tem0, tem1, tem2 column in admin

Answers


Anoop February 2016

You can do this by creating sub queries, Try like this

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'

Post Status

Asked in February 2016
Viewed 2,284 times
Voted 7
Answered 1 times

Search




Leave an answer