Django循环处理两个相同数据的查询,并为每个查询添加成本域

2024-06-07 08:38:48 发布

您现在位置:Python中文网/ 问答频道 /正文

它的标题可能可以更好地措辞,但我挣扎着与它。你知道吗

基本上,我试图从我的模型计算出每个站点的电路成本。电路模型包含如下站点模型:

型号:

class ShowroomConfigData(models.Model):
    location = models.CharField(max_length=50)

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)
    cost_per_month = models.DecimalField(decimal_places=2,max_digits=8)

这可能是如何通过查询来实现的,但是我在前面的一个问题中尝试过,似乎我遇到了一个bug,所以我尝试手动实现它

样本数据:

site a | 1
site a | 2
site a | 5
site b | 100
site b | 2
site d | 666
site d | 1    

所以我想生产

地点a | 8 场地b | 102 场地d | 667

我试着用这种方法来测试:

circuits = CircuitInfoData.objects.all()  
showrooms = ShowroomConfigData.objects.only('location')

for sdata in showrooms:
    for cdata in circuits:
        while cdata.showroom_config_data.location == sdata.location:
         print sdata.location
         print cdata.cost

这个网站刚刚大量生产了8倍的时间。所以我不知道该怎么做?你知道吗

谢谢


Tags: 模型model站点modelssitelocationlengthmax
2条回答

如果你只是用字典呢?每个赛道都有权进入展厅,对吗?因此,如果您构建了一个字典,并在某个特定站点(如果该站点已经被用作键)简单地提取了值,那么您可以简单地添加该值并再次存储它。下面是一个这样做的例子。你知道吗

my_dictionary = dict()
for circuit in circuits:
     if my_dictionary[circuit.showroom_config_data.location] in my_dictionary:
          my_dictionary[circuit.showroom_config_data.location] += circuit.cost_per_month
     else:
          my_dictionary[circuit.showroom_config_data.location] = circuit.cost_per_month

可能并不完全有效,但代码背后的概念将为您提供所需的输出。你知道吗

最有效的方法是使用查询。这可以通过使用annotations实现,方法如下:

from django.db.models import Sum
CircuitInfoData.objects.values("showroom_config_data__location") \
                       .annotate(cost=Sum("cost_per_month"))

例如,这将返回表单中的数据

[{'showroom_config_data__location': u'site a', 'cost': Decimal('30.00')},
 {'showroom_config_data__location': u'site b', 'cost': Decimal('5.00')}]

然后可以格式化此输出

for entry in output:
    print entry["showroom_config_data__location"], " | ", entry["cost"]

得到

site a | 30.00
site b | 5.00

相关问题 更多 >

    热门问题