Iterating list of objects problem

Greetings!

I stuck and need help. I’m getting a list of objects from external API, then I want to iterate them to count how many times each ‘Production’ is in listing. But I’m getting an error and I understand that it is related to the fact that some of records has no name in ‘Production’ field (empty field).

I tried to work around by assigning value ‘Empty’ to empty values, but it doesn’t work. (
Please help.

Error:
|Exception Type:|KeyError|
|Exception Value:|‘Production’|

it points me to the line of code if each['fields']['Production']:

from django.shortcuts import render
import requests 

def partners(request):
    url = "https://somedomain.com/api/v1/zapier/triggers/new-record/xxx?since=2024-01-01T00%3A00%3A00.000Z"
    header = {"Authorization" : "Basic xxx"}
    response = requests.get(url, headers=header)
    records = response.json()

    partners = {}

    for each in records:
        if each['fields']['Production']:
            production = each['fields']['Production']
        else:
            production = 'Empty'
            
        if production in partners.keys():
            partners[production] = partners[production] + 1
        else: 
            partners[production] = + 1

        partners = dict(sorted(partners.items(), key=lambda item: item[1], reverse=True))

    return render(request, 'core/partners.html', {'partners': partners})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Partners</title>
<style>
    body {
        background: #fff8e1;
    }
</style>
</head>
<body>
    <center><b>Partners</b></center>
{% for x,y in partners.items() %}
{{x}}: {{y}}<br><br>
{% endfor %}
</body>
</html>

You’re looking for the dict.get method.

Can be replaced by:

production = each['fields'].get('Production', 'Empty')

This assumes that fields will always exist in each.

1 Like

It works! Thank you!!!

One more question on this topic if I may. Now when I can get a dictionary of ‘name’:‘ocurances’, of couse I’d like also to be able to group them by dates (by month).

The list of objects, that I get by API, includes records for 3 years, each record includes a date of record creation in format ‘2025-03-20T15:30:20.374Z’.

I’d love to group data so I could see dynamic of success with each Production (if it grows or quite opposite). What would be the way to achieve that? Thanks in advance.

That really isn’t a Django question - Django itself isn’t going to have anything to help you with this, unless you save this data to the database and then use the ORM to help organize the results.

Short of that, this becomes an issue of Python coding. You would need to iterate over the results and aggregate the data as needed.

In addition to the normal builtin functions, you might also find the itertools library useful when working on this.