Django模型,过滤器然后组和总成本



我有一个过滤器,我想选择一个提供商,然后对于该提供商显示我们拥有的电路类型和这些电路类型的总成本,从我的研究中,以下应该有效

查询:

model_provider_costs = CircuitInfoData.objects.filter(provider = "BT").values('circuit_type').annotate(total=Sum('cost_per_month'))

它应该给我:

{'circuit_type': u'DSL', 'toal': Decimal('9,457.00')},
{'circuit_type': u'MPLS', 'toal': Decimal('20,000.00')},

,但目前只是给我每个电路,例如:

[
    {'circuit_type': u'DSL', 'total': Decimal('57.00')},
    {'circuit_type': u'MPLS', 'total': Decimal('550.78')},
    {'circuit_type': u'MPLS', 'total': Decimal('547.87')},
    {'circuit_type': u'DSL', 'total': Decimal('57.00')},
    {'circuit_type': u'MPLS', 'total': Decimal('550.78')},
    {'circuit_type': u'DSL', 'total': Decimal('57.00')},
    {'circuit_type': u'MPLS', 'total': Decimal('547.87')},
    ... and so on

这是我的模型:

class CircuitInfoData(models.Model):    
    showroom_config_data = models.ForeignKey(ShowroomConfigData,verbose_name="Install Showroom")
    major_site_info = models.ForeignKey(MajorSiteInfoData,verbose_name="Install Site") 
    circuit_type = models.CharField(max_length=100,choices=settings.CIRCUIT_CHOICES)    
    circuit_speed = models.IntegerField(blank=True)
    circuit_bearer = models.IntegerField(blank=True)
    provider = models.CharField(max_length=200,choices=settings.PROVIDER_CHOICES)
    ref_no = models.CharField(max_length=200,verbose_name="Reference No")
    dsl_username = models.CharField(max_length=200,verbose_name="DSL Username",blank=True)
    dsl_password = models.CharField(max_length=200,verbose_name="DSL Password",blank=True)
    dsl_tel_no = models.CharField(max_length=200,verbose_name="DSL Tel No",blank=True)  
    install_location = models.CharField(max_length=200)
    install_date = models.DateField()
    cost_per_month = models.DecimalField(decimal_places=2,max_digits=8)
    contract_length = models.IntegerField(verbose_name="Contact length in years")
    notes = models.TextField(blank=True)
    service_service_contacts = models.ForeignKey(ServiceContacts)
    subnet = models.GenericIPAddressField(protocol='IPv4',verbose_name="Subnet",blank=True,null=True)
    default_gateway = models.GenericIPAddressField(protocol='IPv4',verbose_name="Default Gateway",blank=True,null=True)
    subnet_mask = models.CharField(max_length=4,verbose_name="Subnet Mask",choices=settings.SUBNET_MASK_CHOICES,blank=True)
    class Meta:
        verbose_name = "Circuit Data"
        verbose_name_plural = "Circuit Data"
        ordering = ('showroom_config_data__location','circuit_speed')
    def __unicode__(self):
        return '%s | %s | %s | %s | %s' % (self.showroom_config_data.location,self.major_site_info.location, self.provider, self.circuit_type, self.ref_no)

它可能应该是

model_provider_costs = CircuitInfoData.objects.filter(provider = "BT").prefetch_related('circuit_type').aggregate(Sum('cost_per_month'))

最新更新