Django:获取物品的方式?

时间:2016-07-16 03:53:28

标签: django python-2.7 django-models django-templates

我有以下模型结构

对于'广告系列的模型'我将写下将在模板中调用的函数:ads_count

我的解决方案是:

class Campaigns(AlphaModel):
    Project = models.ForeignKey('Projects', on_delete=models.CASCADE, related_name='projects')
    ......
    def ads_count(self):
       c = 0
       gr = AdGroups.objects.filter(Campaign=self).all()
       for g in gr:
          c += g.ads_count()
       return c
    ......

class AdGroups(AlphaModel):
    Campaign = models.ForeignKey('Campaigns', on_delete=models.CASCADE, related_name='campaigns')
    server_id = models.PositiveIntegerField()
    ......
    def ads_count(self):
       return Ads.objects.filter(AdGroup=self).count()

    ......
class Ads(AlphaModel):
    AdGroup = models.ForeignKey('AdGroups', on_delete=models.CASCADE, related_name='adgroups_a')
    server_id = models.PositiveIntegerField()
    ......

然而,这会引发错误"无法将关键字解析为字段"

是否有任何简单直接的方法来计算“广告”的对象?属于'广告系列的特定对象' ?

提前致谢!

1 个答案:

答案 0 :(得分:0)

首先,一般惯例是将CamelCase仅用于类定义,并在所有字段名称中使用小写。这使得遵循代码并区分类和对象变得更加容易。我会按如下方式重写你的模型:

class Campaigns(AlphaModel):
    project = models.ForeignKey('Projects', on_delete=models.CASCADE, related_name='projects')

class AdGroups(AlphaModel):
    campaign = models.ForeignKey('Campaigns', on_delete=models.CASCADE, related_name='campaigns')
    server_id = models.PositiveIntegerField()

class Ads(AlphaModel):
    ad_group = models.ForeignKey('AdGroups', on_delete=models.CASCADE, related_name='adgroups_a')
    server_id = models.PositiveIntegerField()

现在,要获得与Ads相关联的Campaign计数,您可以执行此查询:

class Campaigns(AlphaModel):
    ...

    def ads_count(self):
        return Ads.objects.filter(ad_group__campaign=self).count(distinct=True)

(使用您现有的字段名称):

Ads.objects.filter(AdGroup__Campaign=self).count(distinct=True)