[Django]-Nesting multiple 'for' loops

3👍

this should do the very same:

for day in days:
    total_campaigns[day] = Email.objects.filter(day_of_week=day).count()
    # recipients
    total_recipients[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('recipients')).get('recipients__sum', 0.00)
    # unsubscribes
    total_unsubscribes[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('unsubscribes')).get('unsubscribes__sum', 0.00)
    # bounces
    total_bounces[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('bounces')).get('bounces__sum', 0.00)
    # open
    total_open[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('open')).get('open__sum', 0.00)
    # clicks
    total_clicks[day] = Email.objects.filter(day_of_week=day).aggregate(
        Sum('clicks')).get('clicks__sum', 0.00)

and i’m not overly familiar with the django ORM, but you probably can reduce the number of database queries with

for day in days:
    day_objects = Email.objects.filter(day_of_week=day)
    total_campaigns[day] = day_objects.count()
    # recipients
    ...

…etc (and replace all Email.objects.filter(day_of_week=day) with the newly defined day_objects)

0👍

So I’m not totally sure if this is all correct syntax, but perhaps you might try this approach?

def initialize_dict(dict, days, dict_name):
    for day in days:
        if dict_name='':
            dict[day] = Email.objects.filter(day_of_week=day).count()
        else:
            dict[day] = Email.objects.filter(day_of_week=day)
                       .aggregate(Sum(dict_name))
                       .get(dict_name + '__sum', 0.00)

I’m not sure whether this is a better solution, but it is an alternative. You could decide to make the days a global variable instead of having to pass it into the function. A couple of sample calls would be:

initialize_dict(total_campaigns, days, '')
initialize_dict(total_recipients, days, 'recipients')

and so on… I hope this helps. Please feel free to critique this solution on why it is either a good or bad approach! I am still learning and improving myself 🙂

Leave a comment