来自两个表的django admin list_display,没有像外键或很多关系可用的关系

时间:2015-12-14 03:44:06

标签: mysql django caching admin django-queryset

我有两个表,一个是MeasuredController和MeasuredGrid,并且没有外键或多人等关系,在admin中我必须显示MeasuredGrid的两个字段,即power和status,其中MeasuredController的senddate = MeasuredGrid的senddate,in两个不同的列,我已经编写了如下代码,但在当前代码中,每个对象的数据库会被命中两次,那么有没有像select相关或使用缓存概念的方式?

list_display = ("grid_status", "grid_power")

def grid_status(self, obj):
    STATUS_CHOICES = {0:"Outage", 1:"No Outage" }
    mobj = MeasuredGrid.objects.filter(senddate=obj.senddate).latest("senddate")

    try:
        return STATUS_CHOICES[int(mobj.status)], 2
    except:
        pass
grid_status.short_description = 'Grid Status'

def grid_power(self, obj):
    mobj = MeasuredGrid.objects.filter(senddate=obj.senddate).latest("senddate")
    return mobj.power

grid_power.short_description = 'Grid Power[W]'

1 个答案:

答案 0 :(得分:0)

您可以使用Cache Framework。这很容易:

# coding: utf-8
from django.core.cache import cache
from django.contrib import admin

from .models import MeasuredController, MeasuredGrid


class MeasuredControllerAdmin(admin.ModelAdmin):
    list_display = ("grid_status", "grid_power")

    STATUS_CHOICES = {
        0: "Outage",
        1: "No Outage",
    }

    def grid_status(self, obj):
        mobj = self._get_mobj_data(obj)
        return mobj['status']
    grid_status.short_description = 'Grid Status'

    def grid_power(self, obj):
        mobj = self._get_mobj_data(obj)
        return mobj['power']
    grid_power.short_description = 'Grid Power[W]'

    def _get_mobj_data(self, obj):
        """Get a relevant MeasuredGrid object for a given MeasuredController"""

        data = cache.get('mobj_%s' % obj.pk)
        if data is not None:
            return data

        mobj = MeasuredGrid.objects.filter(senddate=obj.senddate).latest("senddate")

        status = None
        try:
            status = self.STATUS_CHOICES[int(mobj.status)], 2
        except: # <---------- Not the best decision. You probably need ValueError or KeyError
            pass

        data = {
            "id": mobj.pk,
            "power": mobj.power,
            "status": status,
        }

        cache.set('mobj_%s' % obj.pk, data) # the default timeout is 300 seconds

        return data

NB:默认缓存后端为django.core.cache.backends.locmem.LocMemCache,因此缓存即使在开发环境中也能正常工作(即。DEBUG = True)。