在Django

时间:2018-01-15 03:05:10

标签: python django performance django-models django-queryset

我有一个相对简单的设置,其中包含一串Parent - > Child关系。

**Parent   Child**
Site     BU
BU       CT
CT       Line
Line     WS
WS       Assess

所以每个孩子都有models.ForeignKey(Parent)

业务逻辑的结构类似于金字塔。

线路级别(1-2-3)取决于所有孩子的WS等级。

CT的等级取决于它的所有等级。

BU在CT水平上的水平 BU级别的站点。

例如:

WS1 \   
WS2 - line 1  --  CT 1 -\ 
WS3 /           /        \
      line 2  -/          \
                  CT 2 --  BU 1 -\
        ..                        Site 1   
        ..        CT 3 --  BU 2 -/
        ..
      line 9  --  CT 4 -/
line 10 -/

以下是问题:

每个级别都有一个属性来设置颜色。 询问网站颜色(金字塔顶部),在我的开发数据库中使用最少量的虚拟数据启动 1266查询。这是一个巨大的数额。

有谁知道如何更好地建模颜色属性?

在只有少数网站的生产服务器上获取网站颜色需要4秒多的时间,目的是添加更多网站。

model.py excerpt:

class CT(models.Model):
    name = models.CharField(max_length=255, blank=False)
    BU = models.ForeignKey(BU, null=True, blank=True, on_delete=models.SET_NULL)
    def __str__(self):
        return "{}".format(self.name)
    def _color(self):
        workstations = self.line_set.all()
        num_of_workstations = len(workstations)
        high_count = 0

        for workstation in workstations:
            if workstation.color == "high":
                high_count = high_count + 1
        elif workstation.color == "No Assessments completed":
            num_of_workstations = num_of_workstations - 1
    if num_of_workstations <=0:
            return "No Assessments completed"
    else:
        if high_count/num_of_workstations > 0.1:
            return "high"
        elif high_count > 0:
            return "medium"
        else:
            return "low"
    color = property(_color)

class Line(models.Model):
    ct= models.ForeignKey(CT, null=True, blank=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=255, blank=False)
    def __str__(self):
        return "{}".format(self.name)

    def _color(self):
        wts = self.wt_set.all()
        num_of_wts = len(wts)
        high_count = 0

        for wt in wts:
            if wt.color == "high":
                high_count = high_count + 1
            elif wt.color == "No Assessments completed":
                num_of_wts = num_of_wts - 1
        if num_of_wts <=0:
            return "No Assessments completed"
        else:
            if high_count/num_of_wts > 0.1:
                return "high"
            elif high_count > 0:
                return "medium"
            else:
                return "low"
    color = property(_color)  


class WS(models.Model):
    line = models.ForeignKey(Line, null=True, blank=True, on_delete=models.SET_NULL)
    def _color(self):
        try:
            latest_assessment = self.assessment_set.latest()
            return latest_assessment.color
        except:
            return "No Assessments completed"
    color=property(_color)

0 个答案:

没有答案