[Fixed]-Django – Looping through two queries for the same data, and adding cost field for each

1πŸ‘

βœ…

The most efficient way to do this is using queries. This can be accomplished using annotations, in the following way:

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

E.g. this will return data in the form

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

You can then format this output

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

To get

site a | 30.00
site b | 5.00
πŸ‘€NS0

0πŸ‘

What if you just used a dictionary? Each circuit will have access to the showroom right? So If you built a dictionary and simply pulled out the value at a particular site if that is already being used as a key, you could simply add the value and store it again. Here is an example of this being done.

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

May not work exactly but the concept behind the code will give you the desired output you are looking for.

πŸ‘€Michael Platt

Leave a comment