Django生成摘要视图

时间:2013-04-25 21:37:36

标签: python django

我有以下型号:

class Model1(models.Model):    
    name = models.CharField(max_length=255, null=True)


class Model2(models.Model):
    model1 = models.ForeignKey(Model1, null=True)
    impressions = models.PositiveIntegerField(default=0)
    clicks = models.PositiveIntegerField(default=0)
    spend = models.PositiveIntegerField(default=0)    
    user = models.ForeignKey(User, null=True)

我正在尝试创建一个视图,其中显示每个模型1登录用户与之关联的广告数量+展示次数,点击次数和支出次数。

快速模型就像:

===================================================
=Model1 Name=Model2 Count=Total Impressions=TotalClicks=
=    First  =       10   =        1        =     1     =
=    Second =        6   =        100      =     20    =
========================================================

我一直在想着为每个model1键设置多个值的dict,但我无法弄清楚如何去做。

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

以下内容应该可以用来获取你所指的词典:

data = {}
for m1 in Model1.objects.all():
    data[m1.name] = Model2.objects.filter(model1=m1)

答案 1 :(得分:0)

最后,我选择了一个存储计算字段列表的字典,如下所示:

data = {}
for m1 in Model1.objects.all():
    list = []
    model2s = m1.model2_set.filter(user=request.user)
    if model2s:
        list.append(calculated field)
        list.append(Another calculated field)    
        data[m1.name] = list